From: "Shot (Piotr Szotkowski)" Date: 2010-06-11T19:10:02+09:00 Subject: Re: comparing objects --1UWUbFP1cBYEclgG Content-Type: text/plain; charset=utf-8 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Rein Henrichs: > #hash makes sense for Hash#[] and etc. #eql? makes more > sense for Array#&. I too find it odd that both are necessary. Both are necessary because #eql? says whether two objects are surely the same, while #hash says whether they=E2=80=99re surely different =E2=80= =93 which, perhaps counterintuitively, is not the same problem. The difference is that in many, many cases it=E2=80=99s much faster to check whether two objects are surely different (via a fast #hash function) than whether they=E2=80=99re surely the same (#eql? can be quite slow). The main difference betwen #eql? and #hash is that #hash can return the same value for objects that are not #eql? (but if two objects are #eql? then #hash must return the same value). An untested, and definitely not optimal (but hopefully simple) example follows. :) Imagine that you want to implement a new immutable string class, one which caches the string length (for performance reasons). Imagine also that the vast majority of such strings you use are of different lenghts, and that you want to use them as Hash keys. class ImmutableString def initialize string @string =3D string.dup.freeze @length =3D string.length end end Given the above assumptions, it might make sense for #hash to return the @length, while #eql? makes the =E2=80=98proper=E2=80=99 comparis= on: class ImmutableString def hash @length end alias eql? =3D=3D end This way in the vast majority of cases, when your ImmutableStrings will be considered for Hash keys, the check whether a given key exists will be very quick; only when two objects #hash to the same value (i.e., when they=E2=80=99re not surely different) the #eql? is called to tell whet= her they=E2=80=99re surely the same. =E2=80=94 Shot --=20 60.times{|a|puts((0..240).map{|b|x=3Dy=3Di=3D0;until(x*x+y*y>4||i=3D=3D99); x,y,i=3Dx*x-y*y+b/120.0-1.5,2*x*y+a/30.0-1,i+1;end;i=3D=3D99?'#':'.'}*'');} [David Brady] --1UWUbFP1cBYEclgG Content-Type: application/pgp-signature; name="signature.asc" Content-Description: Digital signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAkwSC3QACgkQi/mCfdEo8UrzagCeK4Zn6P7op1dKn/NrlBmdaIk6 5YMAn3360cHBs8BCFTZu+c+EqIyiREkw =baZn -----END PGP SIGNATURE----- --1UWUbFP1cBYEclgG--