Delete key from hash if value is empty in Ruby - ruby-on-rails

Given:
data = {:a => 'A', :b => '', :c => 'C', :d => ''}
Objective: To remove key :c and :d if their value is an empty string. However, :a and :b should remain even if their value is an empty string. In the above example, end result should be:
{:a => 'A', :b => '', :c => 'C'}
Current approach:
if data[:c] == ''
data.delete(:c)
end
if data[:d] == ''
data.delete(:d)
end
Is there a better approach to get the same result? (In reality, key of type c and d is more than 10 which result in a long list of if checks.)

You can use Hash#delete_if method
unwanted_keys = [:c, :d]
hash = {:a => 'A', :b => '', :c => 'C', :d => ''}
hash.delete_if{ |k,v| unwanted_keys.include?(k) && v.blank? }
Hope that helps!

You can use Enumerable#each_with_object to build a new hash on the fly applying your conditions:
data.each_with_object({}) do |(k, v), h|
h[k] = v unless %i(c d).include?(k) && v == ''
end
#=> {:a=>"A", :b=>"", :c=>"C"}
As #user000001 suggested in comments, another good option is to use Enumerable#reject:
data.reject { |k, v| %i(c d).include?(k) && v == '' }

you can always just iterate through the list of keys
KEYS_TO_DELETE_IF_BLANK = %i[c d]
KEYS_TO_DELETE_IF_BLANK.each do |key|
data.delete(key) if data[key].blank?
end

You can also use delete if:
data = { :a => 'A', :b => '', :c => 'C', :d => '' }
data.delete_if { |k, value| %i(c d).include?(k) && value.to_s.strip == '' }

you can just use select to extract hash with keys that have values
data = {:a => 'A', :b => '', :c => 'C', :d => ''}
data.select() {|k, v| v.present? || k == :a || k == :b }
# => => {:a=>"A", :b=>"", :c=>"C"}

Related

Rails - Display difference between two Hashes

I have two Hashes hash1 and hash2. Both have the same keys. I need to display the two hashes side by side with the difference between the hashes highlighted in a different color.
How can I do it?
Rails has Hash#diff:
http://apidock.com/rails/Hash/diff
{1 => 2}.diff(1 => 2) # => {}
{1 => 2}.diff(1 => 3) # => {1 => 2}
{}.diff(1 => 2) # => {1 => 2}
{1 => 2, 3 => 4}.diff(1 => 2) # => {3 => 4}
EDIT:
However, this was removed in Rails 4.1.
To get the same result in a more modern project you can use this method, which is derived from the above.
def hash_diff(first, second)
first.
dup.
delete_if { |k, v| second[k] == v }.
merge!(second.dup.delete_if { |k, v| first.has_key?(k) })
end
hash_diff({1 => 2}, {1 => 2}) # => {}
hash_diff({1 => 2}, {1 => 3}) # => {1 => 2}
hash_diff({}, {1 => 2}) # => {1 => 2}
hash_diff({1 => 2, 3 => 4}, {1 => 2}) # => {3 => 4}
Bringing together Unixmonkey answer, Chris Scott's comment and the news that Hash.diff is now deprecated.
Patching Hash
class Hash
def diff(compare_to)
self
.reject { |k, v| compare_to[k] == v }
.merge!(compare_to.reject { |k, _v| self.key?(k) })
end
end
Stand-alone
def hash_diff(a, b)
a
.reject { |k, v| b[k] == v }
.merge!(b.reject { |k, _v| a.key?(k) })
end

Flattening nested hash to a single hash with Ruby/Rails

I want to "flatten" (not in the classical sense of .flatten) down a hash with varying levels of depth, like this:
{
:foo => "bar",
:hello => {
:world => "Hello World",
:bro => "What's up dude?",
},
:a => {
:b => {
:c => "d"
}
}
}
down into a hash with one single level, and all the nested keys merged into one string, so it would become this:
{
:foo => "bar",
:"hello.world" => "Hello World",
:"hello.bro" => "What's up dude?",
:"a.b.c" => "d"
}
but I can't think of a good way to do it. It's a bit like the deep_ helper functions that Rails adds to Hashes, but not quite the same. I know recursion would be the way to go here, but I've never written a recursive function in Ruby.
You could do this:
def flatten_hash(hash)
hash.each_with_object({}) do |(k, v), h|
if v.is_a? Hash
flatten_hash(v).map do |h_k, h_v|
h["#{k}.#{h_k}".to_sym] = h_v
end
else
h[k] = v
end
end
end
flatten_hash(:foo => "bar",
:hello => {
:world => "Hello World",
:bro => "What's up dude?",
},
:a => {
:b => {
:c => "d"
}
})
# => {:foo=>"bar",
# => :"hello.world"=>"Hello World",
# => :"hello.bro"=>"What's up dude?",
# => :"a.b.c"=>"d"}
Because I love Enumerable#reduce and hate lines apparently:
def flatten_hash(param, prefix=nil)
param.each_pair.reduce({}) do |a, (k, v)|
v.is_a?(Hash) ? a.merge(flatten_hash(v, "#{prefix}#{k}.")) : a.merge("#{prefix}#{k}".to_sym => v)
end
end
irb(main):118:0> flatten_hash(hash)
=> {:foo=>"bar", :"hello.world"=>"Hello World", :"hello.bro"=>"What's up dude?", :"a.b.c"=>"d"}
The top voted answer here will not flatten the object all the way, it does not flatten arrays. I've corrected this below and have offered a comparison:
x = { x: 0, y: { x: 1 }, z: [ { y: 0, x: 2 }, 4 ] }
def top_voter_function ( hash )
hash.each_with_object( {} ) do |( k, v ), h|
if v.is_a? Hash
top_voter_function( v ).map do |h_k, h_v|
h[ "#{k}.#{h_k}".to_sym ] = h_v
end
else
h[k] = v
end
end
end
def better_function ( a_el, a_k = nil )
result = {}
a_el = a_el.as_json
a_el.map do |k, v|
k = "#{a_k}.#{k}" if a_k.present?
result.merge!( [Hash, Array].include?( v.class ) ? better_function( v, k ) : ( { k => v } ) )
end if a_el.is_a?( Hash )
a_el.uniq.each_with_index do |o, i|
i = "#{a_k}.#{i}" if a_k.present?
result.merge!( [Hash, Array].include?( o.class ) ? better_function( o, i ) : ( { i => o } ) )
end if a_el.is_a?( Array )
result
end
top_voter_function( x ) #=> {:x=>0, :"y.x"=>1, :z=>[{:y=>0, :x=>2}, 4]}
better_function( x ) #=> {"x"=>0, "y.x"=>1, "z.0.y"=>0, "z.0.x"=>2, "z.1"=>4}
I appreciate that this question is a little old, I went looking online for a comparison of my code above and this is what I found. It works really well when used with events for an analytics service like Mixpanel.
Or if you want a monkey-patched version or Uri's answer to go your_hash.flatten_to_root:
class Hash
def flatten_to_root
self.each_with_object({}) do |(k, v), h|
if v.is_a? Hash
v.flatten_to_root.map do |h_k, h_v|
h["#{k}.#{h_k}".to_sym] = h_v
end
else
h[k] = v
end
end
end
end
In my case I was working with the Parameters class so none of the above solutions worked for me. What I did to resolve the problem was to create the following function:
def flatten_params(param, extracted = {})
param.each do |key, value|
if value.is_a? ActionController::Parameters
flatten_params(value, extracted)
else
extracted.merge!("#{key}": value)
end
end
extracted
end
Then you can use it like flatten_parameters = flatten_params(params). Hope this helps.
Just in case, that you want to keep their parent
def flatten_hash(param)
param.each_pair.reduce({}) do |a, (k, v)|
v.is_a?(Hash) ? a.merge({ k.to_sym => '' }, flatten_hash(v)) : a.merge(k.to_sym => v)
end
end
hash = {:foo=>"bar", :hello=>{:world=>"Hello World", :bro=>"What's up dude?"}, :a=>{:b=>{:c=>"d"}}}
flatten_hash(hash)
# {:foo=>"bar", :hello=>"", :world=>"Hello World", :bro=>"What's up dude?", :a=>"", :b=>"", :c=>"d"}

In Rails, what is the best way to compact a hash into a nested hash

Say I have this:
[
{ :user_id => 1, :search_id => a},
{ :user_id => 1, :search_id => b},
{ :user_id => 2, :search_id => c},
{ :user_id => 2, :search_id => d}
]
and I want to end up with:
[
{ :user_id => 1, :search_id => [a,b]},
{ :user_id => 2, :search_id => [c,d]}
]
What is the best way to do that?
Very strange requirement indeed. Anyway
[ { :user_id => 1, :search_id => "a"},
{ :user_id => 1, :search_id => "b"},
{ :user_id => 2, :search_id => "c"},
{ :user_id => 2, :search_id => "d"} ] \
.map{ |h| h.values_at(:user_id, :search_id) } \
.group_by(&:first) \
.map{ |k, v| { :user_id => k, :search_id => v.map(&:last) } }
array.group_by{|x| x[:user_id] }.values.map do |val|
{ user_id: val.first[:user_id],
search_id: val.inject([]){|me, el| me << el[:search_id]} }
end
First off, I think the cleaner output structure here is to allow the user IDs to be the hash keys and the list of search IDs to be the values:
{
1 => [a, b],
2 => [c, d]
}
There might be a clever way using Rails helpers to get this structure, but it's not too bad to do it manually, either:
output = {}
input.each do |row|
key = row[:user_id]
value = row[:search_id]
output[key] ||= []
output[key] << value
end
I agree with Matchus representation of the data and just want to suggest a shorter version for it (input being the initial array).
input.each.with_object(Hash.new {|h,k| h[k] = []}) do |k,o|
o[k[:user_id]] << k[:search_id]
end
EDIT: this is Ruby > 1.9
input.inject({}) do
|m, h| (m[h[:user_id]] ||= []) << h[:search_id]; m
end.inject([]) { |m, (k, v)| m << { :user_id => k, :search_id => v }; m }

Merging multi-dimensional hashes in Ruby

I have two hashes which have a structure something similar to this:
hash_a = { :a => { :b => { :c => "d" } } }
hash_b = { :a => { :b => { :x => "y" } } }
I want to merge these together to produce the following hash:
{ :a => { :b => { :c => "d", :x => "y" } } }
The merge function will replace the value of :a in the first hash with the value of :a in the second hash. So, I wrote my own recursive merge function, which looks like this:
def recursive_merge( merge_from, merge_to )
merged_hash = merge_to
first_key = merge_from.keys[0]
if merge_to.has_key?(first_key)
merged_hash[first_key] = recursive_merge( merge_from[first_key], merge_to[first_key] )
else
merged_hash[first_key] = merge_from[first_key]
end
merged_hash
end
But I get a runtime error: can't add a new key into hash during iteration. What's the best way of going about merging these hashes in Ruby?
Ruby's existing Hash#merge allows a block form for resolving duplicates, making this rather simple. I've added functionality for merging multiple conflicting values at the 'leaves' of your tree into an array; you could choose to pick one or the other instead.
hash_a = { :a => { :b => { :c => "d", :z => 'foo' } } }
hash_b = { :a => { :b => { :x => "y", :z => 'bar' } } }
def recurse_merge(a,b)
a.merge(b) do |_,x,y|
(x.is_a?(Hash) && y.is_a?(Hash)) ? recurse_merge(x,y) : [*x,*y]
end
end
p recurse_merge( hash_a, hash_b )
#=> {:a=>{:b=>{:c=>"d", :z=>["foo", "bar"], :x=>"y"}}}
Or, as a clean monkey-patch:
class Hash
def merge_recursive(o)
merge(o) do |_,x,y|
if x.respond_to?(:merge_recursive) && y.is_a?(Hash)
x.merge_recursive(y)
else
[*x,*y]
end
end
end
end
p hash_a.merge_recursive hash_b
#=> {:a=>{:b=>{:c=>"d", :z=>["foo", "bar"], :x=>"y"}}}
You can do it in one line :
merged_hash = hash_a.merge(hash_b){|k,hha,hhb| hha.merge(hhb){|l,hhha,hhhb| hhha.merge(hhhb)}}
If you want to imediatly merge the result into hash_a, just replace the method merge by the method merge!
If you are using rails 3 or rails 4 framework, it is even easier :
merged_hash = hash_a.deep_merge(hash_b)
or
hash_a.deep_merge!(hash_b)
If you change the first line of recursive_merge to
merged_hash = merge_to.clone
it works as expected:
recursive_merge(hash_a, hash_b)
-> {:a=>{:b=>{:c=>"d", :x=>"y"}}}
Changing the hash as you move through it is troublesome, you need a "work area" to accumulate your results.
Try this monkey-patching solution:
class Hash
def recursive_merge(hash = nil)
return self unless hash.is_a?(Hash)
base = self
hash.each do |key, v|
if base[key].is_a?(Hash) && hash[key].is_a?(Hash)
base[key].recursive_merge(hash[key])
else
base[key]= hash[key]
end
end
base
end
end
In order to merge one into the other as the ticket suggested, you could modify #Phrogz function
def recurse_merge( merge_from, merge_to )
merge_from.merge(merge_to) do |_,x,y|
(x.is_a?(Hash) && y.is_a?(Hash)) ? recurse_merge(x,y) : x
end
end
In case there is duplicate key, it will only use the content of merge_from hash
Here is even better solution for recursive merging that uses refinements and has bang method alongside with block support. This code does work on pure Ruby.
module HashRecursive
refine Hash do
def merge(other_hash, recursive=false, &block)
if recursive
block_actual = Proc.new {|key, oldval, newval|
newval = block.call(key, oldval, newval) if block_given?
[oldval, newval].all? {|v| v.is_a?(Hash)} ? oldval.merge(newval, &block_actual) : newval
}
self.merge(other_hash, &block_actual)
else
super(other_hash, &block)
end
end
def merge!(other_hash, recursive=false, &block)
if recursive
self.replace(self.merge(other_hash, recursive, &block))
else
super(other_hash, &block)
end
end
end
end
using HashRecursive
After using HashRecursive was executed you can use default Hash::merge and Hash::merge! as if they haven't been modified. You can use blocks with these methods as before.
The new thing is that you can pass boolean recursive (second argument) to these modified methods and they will merge hashes recursively.
Example usage for answering the question. It's extremely easy:
hash_a = { :a => { :b => { :c => "d" } } }
hash_b = { :a => { :b => { :x => "y" } } }
puts hash_a.merge(hash_b) # Won't override hash_a
# output: { :a => { :b => { :x => "y" } } }
puts hash_a # hash_a is unchanged
# output: { :a => { :b => { :c => "d" } } }
hash_a.merge!(hash_b, recursive=true) # Will override hash_a
puts hash_a # hash_a was changed
# output: { :a => { :b => { :c => "d", :x => "y" } } }
For advanced example take a look at this answer.
Also take a look at my recursive version of Hash::each(Hash::each_pair) here.

Converting Ruby hashes to arrays

I have a Hash which is of the form
{:a => {"aa" => 11,"ab" => 12}, :b => {"ba" => 21,"bb" => 22}}
How do i convert it to the form {:a => [["aa",11],["ab",12]],:b=>[["ba",21],["bb",22]]}
If you want to modify the original hash you can do:
hash.each_pair { |key, value| hash[key] = value.to_a }
From the documentation for Hash#to_a
Converts hsh to a nested array of [
key, value ] arrays.
h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
h.to_a #=> [["c", 300], ["a", 100], ["d", 400]]
Here is another way to do this :
hsh = {:a => {"aa" => 11,"ab" => 12}, :b => {"ba" => 21,"bb" => 22}}
hsh.each{|k,v| hsh[k]=*v}
# => {:a=>[["aa", 11], ["ab", 12]], :b=>[["ba", 21], ["bb", 22]]}
hash.collect {|a, b| [a, hash[a].collect {|c,d| [c,d]}] }.collect {|e,f| [e => f]}

Resources