Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash merge with one of hash having key as a symbol

Tags:

ruby

hash

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"}.

like image 723
user27111987 Avatar asked Sep 16 '25 05:09

user27111987


1 Answers

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.

like image 152
spickermann Avatar answered Sep 17 '25 19:09

spickermann