How do you compare hashes for equality that contain different key formats (some strings, some characters) in Ruby?

I am using ruby ​​1.9.3 and I need to compare two hashes that have different key formats. For example, I want the equality of the following two hashes to be true:

hash_1 = {:date => 2011-11-01, :value => 12}
hash_2 = {"date" => 2011-11-01, "value" => 12}

      

Any ideas on how these two hashes can be compared in the same line of code?

+3


source to share


1 answer


Flatten hash keys containing characters:

 > hash_1.stringify_keys
=> {"date"=>"2011-11-01", "value"=>12} 

      

Then compare. So your answer is in one line:

 > hash_1.stringify_keys == hash_2    
=> true

      

You can also do it the other way around by symbolizing string keys in hash_2

instead of specifying them in hash_1

:

 > hash_1 == hash_2.symbolize_keys
=> true

      

If you want the strobing / symbolization to be a permanent change, use the bang !

: version stringify_keys!

or symbolize_keys!

respectively

 > hash_1.stringify_keys!                # <- Permanently changes the keys in hash_1 into Strings
=> {"date"=>"2011-11-01", "value"=>12}   #    as opposed to temporarily changing them for comparison

      



Link: http://as.rubyonrails.org/classes/HashWithIndifferentAccess.html

Also, I'm assuming you wanted to put quotes around dates ...

:date => "2011-11-01"

... or explicitly instantiate as Date objects?

:date => Date.new("2011-11-01")

The way you specified the date now sets :date

to 2011-11-01

. They are currently interpreted as integers with a subtraction between them.

I.e:

 > date = 2011-11-01
=> 1999                # <- integer value of 2011, minus 11, minus 1

      

+3


source







All Articles