1st send attempt died in spamassassin...

---------- Forwarded message ----------
From: Robert Klemme <shortcutter / googlemail.com>
Date: Sat, Jul 16, 2011 at 12:21 AM
Subject: Re: Comparing hashes based on their keys
To: ruby-talk / ruby-lang.org


On Fri, Jul 15, 2011 at 9:47 PM, Rob Biedenharn
<Rob / agileconsultingllc.com> wrote:
> On Jul 15, 2011, at 3:01 PM, Stefano Mioli wrote:
>
>> On 7/15/11 7:18 PM, Rob Biedenharn wrote:
>>
>> class Hash
>> =A0def same_key_structure?(other)
>> =A0 return false unless other.is_a?(Hash)
>> =A0 return false unless self.keys =3D=3D other.keys &&
>> self.keys.all?{|_|_.is_a?(Symbol)}
>> =A0 self.keys.all? {|_|self[_].is_a?(Hash) ?
>> self[_].same_key_structure?(other[_]) : !other[_].is_a?(Hash)}
>> =A0end
>> end
>>
>>
>> Now that I think about it, that
>>
>> =A0 =A0 =A0 =A0self.keys =3D=3D 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:
>>
>> =A0 =A0 =A0 =A0h1 =3D {:x =3D> nil, :y =3D> nil}
>> =A0 =A0 =A0 =A0h2 =3D {:y =3D> nil, :x =3D> nil}
>>
>> but h1.keys =3D=3D h2.keys would return false in this context.
>
> =A0then sort them:
>
> =A0return false unless self.keys.sort =3D=3D other.keys.sort

There is one reason to not sort: Hash keys are not required to
implement <=3D>. =A0Now, we "know" that keys will be only Symbols but what
if not? =A0You might see an exception from #sort. =A0Comparing via Set
would be more robust here since we know that keys fulfill the
requirements for a Set element. =A0So that would be

return false unless keys.to_set =3D=3D other.keys.to_set

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/