From: Rob Biedenharn Date: 2011-07-16T04:47:54+09:00 Subject: Re: Comparing hashes based on their keys On Jul 15, 2011, at 3:01 PM, Stefano Mioli wrote: > On 7/15/11 7:18 PM, Rob Biedenharn wrote: > > class Hash > def same_key_structure?(other) > return false unless other.is_a?(Hash) > return false unless self.keys == other.keys && self.keys.all?{|_| > _.is_a?(Symbol)} > self.keys.all? {|_|self[_].is_a?(Hash) ? > self[_].same_key_structure?(other[_]) : !other[_].is_a?(Hash)} > end > end > > > Now that I think about it, that > > self.keys == other.keys > > might cause problems, because I didn't specify (sorry, my bad) that > I don't care about which order the keys appear in. > > In other words, I consider these two hashes to be equal: > > h1 = {:x => nil, :y => nil} > h2 = {:y => nil, :x => nil} > > but h1.keys == h2.keys would return false in this context. then sort them: return false unless self.keys.sort == other.keys.sort Since they are Hashes, I'd certainly hope that the order of the keys didn't matter. ;-) I should have realized that particularly since 1.9.2's Hashes return their keys in an order dependent on their insertion to the Hash. (And I gave a talk to the Cincinnati Ruby Brigade just last month about differences between 1.8.6 and 1.9.2 that included this fact.) -Rob > > Array could probably benefit from something like RSpec's '=~' to > test arrays for equality regardless of the order of their elements, > wouldn't it? > That is, unless I'm missing some existing method that does that. > > -- > Stefano Mioli > Rob Biedenharn Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/ rab@GaslightSoftware.com http://GaslightSoftware.com/