I have two hash in Ruby like this
hash1={"a" = > "b"}
hash2={:a => "c" }
When I am doing hash1.merge!(hash2) I am getting the result as
{"a"=>"b", :a=>"c"}
I want to get the result as {"a" => "c"}
basically I want ruby to treat symbol and string as same for key value.
I was looking into Hash class and could not find any way to do so.
Question is how can I merge such that result of above operation is {"a" => "c"}.
The ActiveSupport
gem has the Hash#stringify_keys
method that helps in this case:
require 'active_support/hash_with_indifferent_access'
hash1 = { "a" => "b" }
hash2 = { :a => "c" }
hash1.merge(hash2.stringify_keys)
# => { "a" => "c" }
This is how the method is implemented (simplified):
class Hash
def stringify_keys
{}.tap do |result|
each_key { |key| result[key.to_s] = self[key] }
end
end
end
Update Ruby 2.5.0 introduced Array#transform_keys
that would allow stringifying keys in a hash like this:
hash1 = { "a" => "b" }
hash2 = { :a => "c" }
hash1.merge(hash2.transform_keys(&:to_s))
# => { "a" => "c" }
That means there is no need to use ActiveSupport
anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With