I’m 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 the 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 one line of code?
Stringify the keys on the hash that has symbols:
Then compare. So, your answer, in one line, is:
You could also do it the other way around, symbolizing the string keys in
hash_2instead of stringifying them inhash_1:If you want the stringification/symbolization to be a permanent change, use the version with the bang
!:stringify_keys!orsymbolize_keys!respectivelyRef: http://as.rubyonrails.org/classes/HashWithIndifferentAccess.html
Also, I’m guessing you meant to put quotes around the dates…
:date => "2011-11-01"…or, explicitly instantiate them as Date objects?
:date => Date.new("2011-11-01")The way you have the date written now sets
:dateto2011-11-01These are currently being interpreted as series of integers with subtraction in between them.That is: