From two hashes obtain another with keys non repeated in ruby - ruby

I have two hashes in ruby and I want compare both and then create another with the keys and values of non repeated keys.
A = {"name1" => 123, "name2" => 321, "name3" => 412 }
B = {"name1" => 412, "name2" => 412, "name4" => 444}
I want compare B with A, and obtain a new hash with the keys and values of the keys that are not present in A.
C = {"name4" => 444}
Could you help me please?
Thanks
Regards

You can use Hash#select or Hash#reject without the bang:
C = B.select { |k, _| !A[k] }
#=> {"name4"=>444}
B.reject { |k, _| A[k] }
#=> {"name4"=>444}
If your hash contains boolean values, use nil? method (A[k].nil?) or Hash#has_key? (A.has_key?).
Also you can use Hash#delete_if method:
C = B.delete_if { |k, v| A.has_key?(k) }
#=> {"name4"=>444}

Related

Implement merge method in ruby

I'm trying to implement merge method in my code.
A = { "a" => 200, "b" => 100 }
B = { "b" => 100, "c" => 300 }
So when I call A.merge_method(B) in my main function, it should return
A.merge_method(B) #=> {"a"=>200, "b"=>200, "c"=>300}
How can I implement without using merge method?
Here is the general idea: collect all the keys of any hashes to be merged, then for each of the keys, collect the values in all the hashes that have that key, and sum them.
module HashWithMergeReduce
refine Hash do
def merge_reduce(*others, &op)
hashes = [self, *others]
hash_keys = hashes.map(&:keys).inject(Set.new, &:+)
hash_keys.each do |key|
hashes_with_key = hashes.select { |hash| hash.has_key?(key) }
self[key] = hashes_with_key.map { |hash| hash[key] }.reduce(&op)
end
self
end
end
end
module TestHashWithMergeReduce
using HashWithMergeReduce
a = { "a" => 200, "b" => 100 }
b = { "b" => 100, "c" => 300 }
puts a.merge_reduce(b, &:+)
# => {"a"=>200, "b"=>200, "c"=>300}
end
I can't bring myself to add the method merge_method to the class Hash, not only because it contaminates a core class, but also because it's only applicable to a small subset of hashes, ones for which all values are numeric.
One could refine Hash, as #Amadan has done, but I think it makes more sense to simply create a method similar to module methods that behave as functions (e.g, Math::sqrt), that takes all hashes as arguments.
def sum_values_by_key(*hashes)
hashes.each_with_object(Hash.new(0)) { |g,h| g.each { |k,v| h[k] += v } }
end
sum_values_by_key({ "a" => 200, "b" => 100 }, { "b" => 100, "c" => 300 })
#=> {"a"=>200, "b"=>200, "c"=>300}
sum_values_by_key({ "a" => 200, "b" => 100 }, { "b" => 100, "c" => 300 },
{ "a" => 150, "c" => 250 })
#=> {"a"=>350, "b"=>200, "c"=>550}
This uses the form of Hash::new that defines a default value, which here is zero. The expression:
h[k] += v
expands to:
h[k] = h[k] + v
If this hash has been defined h = Hash.new(0) and h has a key k, h[k] on the right of the equality is evaluated to return the value of k. If, however, h does not have a key k, h[k] on the right returns the default value, zero, to become:
h[k] = 0 + v
I've also changed the method name to make it more meaningful.

Ruby: Swap out hash key with matching value from other hash

I have these hashes:
hash = {1 => "popcorn", 2 => "soda"}
other_hash = {1 => "dave", 2 => "linda", 3 => "bobby_third_wheel"}
I would like to replace the id reference with the name associated to the id in the second hash, if there is a record in other_hash that has nothing to match, it should just be dropped in the resulting hash. Like this:
the_one_hash_to_rule_them_all = {"dave" => "popcorn", "linda" => "soda"}
You can easly use this each_with_object method on "primary" hash with names.
other_hash.each_with_object({}) { |(id, name), h| h[name] = hash[id] if hash.key?(id) }
# => {"dave"=>"popcorn", "linda"=>"soda"}
hash.each_with_object({}){|(k,v), res| res[other_hash[k]] = v}
# => {"dave"=>"popcorn", "linda"=>"soda"}
First, an "array-comprehension" with the pattern enumerable.map { expr if condition }.compact and finally an Array#to_h.
h = other_hash.map { |k, v| [v, hash[k]] if hash.has_key?(k) }.compact.to_h
#=> {"dave"=>"popcorn", "linda"=>"soda"}
Also:
h = other_hash.select { |k, v| hash.has_key?(k) }.map { |k, v| [v, hash[k]] }.to_h
hash.map{|k, v| [other_hash[k], v]}.to_h
# => {"dave"=>"popcorn", "linda"=>"soda"}

Ruby / Remove everything after a matched key / array of hashes

Let's say I have the following array of hashes:
h = [{"name" => "bob"}, {"car" => "toyota"}, {"age" => "25"}]
And I have the following key to match:
k = 'car'
How do I match the 'k' to 'h' and have delete every element after the match so that it returns:
h = [{"name" => "bob"}, {"car" => "toyota"}]
Just convert hash to array, do your task and then convert back
h = {"name" => "bob", "car" => "toyota", "age" => "25"}
array = h.to_a.flatten
index = array.index('car') + 1
h = Hash[*array[0..index]]
=> {"name"=>"bob", "car"=>"toyota"}
By the way, the hash is ordered only since Ruby 1.9
ar = [{"name" => "bob"}, {"car" => "toyota"}, {"age" => "25"}]
p ar[0 .. ar.index{|h| h.key?('car')}] #=>[{"name"=>"bob"}, {"car"=>"toyota"}]
I like megas' version, as its short and to the point. Another approach, which would be more explicit, would be iterating over the keys array of each hash. The keys of a hash are maintained in an ordered array (http://ruby-doc.org/core-1.9.3/Hash.html). They are ordered by when they were first entered. As a result, you can try the following:
newArray = Array.new
h.each do |hash| # Iterate through your array of hashes
newArray << hash
if hash.has_key?("car") # check if this hash is the "car" hash.
break # exits the block
end
end
This all depends, of course, on whether the array was created in the proper order. If it was, then you're golden.
A hash is unordered set by definition, so what you request is somewhat undefined. However you can do something like a hack:
h = {"name" => "bob", "car" => "toyota", "age" => "25"}
matched = false
key_given = "car"
h.each do |k,v|
if matched
h.delete(k)
end
if k == key_given
matched = true
next
end
end
I'm pretty late to the party here. I was looking for a solution to this same problem, but I didn't love these answers. So, here's my approach:
class Array
def take_until(&blk)
i = find_index &blk
take(i + 1)
end
end
h = [{"name" => "bob"}, {"car" => "toyota"}, {"age" => "25"}]
k = 'car'
h.take_until { |x| x.has_key?(k) }
=> [{"name"=>"bob"}, {"car"=>"toyota"}]

How do I convert a Ruby hash so that all of its keys are symbols?

I have a Ruby hash which looks like:
{ "id" => "123", "name" => "test" }
I would like to convert it to:
{ :id => "123", :name => "test" }
hash = {"apple" => "banana", "coconut" => "domino"}
Hash[hash.map{ |k, v| [k.to_sym, v] }]
#=> {:apple=>"banana", :coconut=>"domino"}
#mu is too short: Didn't see word "recursive", but if you insist (along with protection against non-existent to_sym, just want to remind that in Ruby 1.8 1.to_sym == nil, so playing with some key types can be misleading):
hash = {"a" => {"b" => "c"}, "d" => "e", Object.new => "g"}
s2s =
lambda do |h|
Hash === h ?
Hash[
h.map do |k, v|
[k.respond_to?(:to_sym) ? k.to_sym : k, s2s[v]]
end
] : h
end
s2s[hash] #=> {:d=>"e", #<Object:0x100396ee8>=>"g", :a=>{:b=>"c"}}
If you happen to be in Rails then you'll have symbolize_keys:
Return a new hash with all keys converted to symbols, as long as they respond to to_sym.
and symbolize_keys! which does the same but operates in-place. So, if you're in Rails, you could:
hash.symbolize_keys!
If you want to recursively symbolize inner hashes then I think you'd have to do it yourself but with something like this:
def symbolize_keys_deep!(h)
h.keys.each do |k|
ks = k.to_sym
h[ks] = h.delete k
symbolize_keys_deep! h[ks] if h[ks].kind_of? Hash
end
end
You might want to play with the kind_of? Hash to match your specific circumstances; using respond_to? :keys might make more sense. And if you want to allow for keys that don't understand to_sym, then:
def symbolize_keys_deep!(h)
h.keys.each do |k|
ks = k.respond_to?(:to_sym) ? k.to_sym : k
h[ks] = h.delete k # Preserve order even when k == ks
symbolize_keys_deep! h[ks] if h[ks].kind_of? Hash
end
end
Note that h[ks] = h.delete k doesn't change the content of the Hash when k == ks but it will preserve the order when you're using Ruby 1.9+. You could also use the [(key.to_sym rescue key) || key] approach that Rails uses in their symbolize_keys! but I think that's an abuse of the exception handling system.
The second symbolize_keys_deep! turns this:
{ 'a' => 'b', 'c' => { 'd' => { 'e' => 'f' }, 'g' => 'h' }, ['i'] => 'j' }
into this:
{ :a => 'b', :c => { :d => { :e => 'f' }, :g => 'h' }, ['i'] => 'j' }
You could monkey patch either version of symbolize_keys_deep! into Hash if you really wanted to but I generally stay away from monkey patching unless I have very good reasons to do it.
If you are using Rails >= 4 you can use:
hash.deep_symbolize_keys
hash.deep_symbolize_keys!
or
hash.deep_stringify_keys
hash.deep_stringify_keys!
see http://apidock.com/rails/v4.2.1/Hash/deep_symbolize_keys
Just in case you are parsing JSON, from the JSON docs you can add the option to symbolize the keys upon parsing:
hash = JSON.parse(json_data, symbolize_names: true)
Victor Moroz provided a lovely answer for the simple recursive case, but it won't process hashes that are nested within nested arrays:
hash = { "a" => [{ "b" => "c" }] }
s2s[hash] #=> {:a=>[{"b"=>"c"}]}
If you need to support hashes within arrays within hashes, you'll want something more like this:
def recursive_symbolize_keys(h)
case h
when Hash
Hash[
h.map do |k, v|
[ k.respond_to?(:to_sym) ? k.to_sym : k, recursive_symbolize_keys(v) ]
end
]
when Enumerable
h.map { |v| recursive_symbolize_keys(v) }
else
h
end
end
Try this:
hash = {"apple" => "banana", "coconut" => "domino"}
# => {"apple"=>"banana", "coconut"=>"domino"}
hash.tap do |h|
h.keys.each { |k| h[k.to_sym] = h.delete(k) }
end
# => {:apple=>"banana", :coconut=>"domino"}
This iterates over the keys, and for each one, it deletes the stringified key and assigns its value to the symbolized key.
If you're using Rails (or just Active Support):
{ "id" => "123", "name" => "test" }.symbolize_keys
Starting with Ruby 2.5 you can use the transform_key method.
So in your case it would be:
h = { "id" => "123", "name" => "test" }
h.transform_keys!(&:to_sym) #=> {:id=>"123", :name=>"test"}
Note: the same methods are also available on Ruby on Rails.
Here's a Ruby one-liner that is faster than the chosen answer:
hash = {"apple" => "banana", "coconut" => "domino"}
#=> {"apple"=>"banana", "coconut"=>"domino"}
hash.inject({}){|h,(k,v)| h[k.intern] = v; h}
#=> {:apple=>"banana", :coconut=>"domino"}
Benchmark results:
n = 100000
Benchmark.bm do |bm|
bm.report { n.times { hash.inject({}){|h,(k,v)| h[k.intern] = v; h} } }
bm.report { n.times { Hash[hash.map{ |k, v| [k.to_sym, v] }] } }
end
# => user system total real
# => 0.100000 0.000000 0.100000 ( 0.107940)
# => 0.120000 0.010000 0.130000 ( 0.137966)
I'm partial to:
irb
ruby-1.9.2-p290 :001 > hash = {"apple" => "banana", "coconut" => "domino"}
{
"apple" => "banana",
"coconut" => "domino"
}
ruby-1.9.2-p290 :002 > hash.inject({}){ |h, (n,v)| h[n.to_sym] = v; h }
{
:apple => "banana",
:coconut => "domino"
}
This works because we're iterating over the hash and building a new one on the fly. It isn't recursive, but you could figure that out from looking at some of the other answers.
hash.inject({}){ |h, (n,v)| h[n.to_sym] = v; h }
You can also extend core Hash ruby class placing a /lib/hash.rb file :
class Hash
def symbolize_keys_deep!
new_hash = {}
keys.each do |k|
ks = k.respond_to?(:to_sym) ? k.to_sym : k
if values_at(k).first.kind_of? Hash or values_at(k).first.kind_of? Array
new_hash[ks] = values_at(k).first.send(:symbolize_keys_deep!)
else
new_hash[ks] = values_at(k).first
end
end
new_hash
end
end
If you want to make sure keys of any hash wrapped into arrays inside your parent hash are symbolized, you need to extend also array class creating a "array.rb" file with that code :
class Array
def symbolize_keys_deep!
new_ar = []
self.each do |value|
new_value = value
if value.is_a? Hash or value.is_a? Array
new_value = value.symbolize_keys_deep!
end
new_ar << new_value
end
new_ar
end
end
This allows to call "symbolize_keys_deep!" on any hash variable like this :
myhash.symbolize_keys_deep!
def symbolize_keys(hash)
new={}
hash.map do |key,value|
if value.is_a?(Hash)
value = symbolize_keys(value)
end
new[key.to_sym]=value
end
return new
end
puts symbolize_keys("c"=>{"a"=>2,"k"=>{"e"=>9}})
#{:c=>{:a=>2, :k=>{:e=>9}}}
Here's my two cents,
my version of symbolize_keys_deep! uses the original symbolize_keys! provided by rails and just makes a simple recursive call to Symbolize sub hashes.
def symbolize_keys_deep!(h)
h.symbolize_keys!
h.each do |k, v|
symbolize_keys_deep!(v) if v.is_a? Hash
end
end
Facets' Hash#rekey is also a worth mentioning.
Sample:
require 'facets/hash/rekey'
{ "id" => "123", "name" => "test" }.deep_rekey
=> {:id=>"123", :name=>"test"}
There is also a recursive version:
require 'facets/hash/deep_rekey'
{ "id" => "123", "name" => {"first" => "John", "last" => "Doe" } }.deep_rekey
=> {:id=>"123", :name=>{:first=>"John", :last=>"Doe"}}
Here's a little recursive function to do a deep symbolization of the keys:
def symbolize_keys(hash)
Hash[hash.map{|k,v| v.is_a?(Hash) ? [k.to_sym, symbolize_keys(v)] : [k.to_sym, v] }]
end

Ruby: What is the easiest method to update Hash values?

Say:
h = { 1 => 10, 2 => 20, 5 => 70, 8 => 90, 4 => 34 }
I would like to change each value v to foo(v), such that h will be:
h = { 1 => foo(10), 2 => foo(20), 5 => foo(70), 8 => foo(90), 4 => foo(34) }
What is the most elegant way to achieve this ?
You can use update (alias of merge!) to update each value using a block:
hash.update(hash) { |key, value| value * 2 }
Note that we're effectively merging hash with itself. This is needed because Ruby will call the block to resolve the merge for any keys that collide, setting the value with the return value of the block.
Rails (and Ruby 2.4+ natively) have Hash#transform_values, so you can now do {a:1, b:2, c:3}.transform_values{|v| foo(v)}
https://ruby-doc.org/core-2.4.0/Hash.html#method-i-transform_values
If you need it to work in nested hashes as well, Rails now has deep_transform_values(source):
hash = { person: { name: 'Rob', age: '28' } }
hash.deep_transform_values{ |value| value.to_s.upcase }
# => {person: {name: "ROB", age: "28"}}
This will do:
h.each {|k, v| h[k] = foo(v)}
The following is slightly faster than #Dan Cheail's for large hashes, and is slightly more functional-programming style:
new_hash = Hash[old_hash.map {|key, value| key, foo(value)}]
Hash#map creates an array of key value pairs, and Hash.[] converts the array of pairs into a hash.
There's a couple of ways to do it; the most straight-forward way would be to use Hash#each to update a new hash:
new_hash = {}
old_hash.each do |key, value|
new_hash[key] = foo(value)
end

Resources