From: Josh Cheek Date: 2011-12-30T18:44:09+09:00 Subject: Re: What’s the standard way of implementing #hash for value objects in Ruby? --bcaec53f395b5bb33204b54c1211 Content-Type: text/plain; charset=windows-1252 Content-Transfer-Encoding: quoted-printable On Fri, Dec 30, 2011 at 3:09 AM, Nikolai Weibull wrote: > On Fri, Dec 30, 2011 at 06:25, Josh Cheek wrote: > > On Thu, Dec 29, 2011 at 5:47 PM, Nikolai Weibull wrote: > >> So, again, what=92s the standard way of implementing #hash for value > objects in Ruby? > > > If there is one, I don't know what it is, which implies there isn't one= . > > That=92s a very bold statement to make, considering that you don=92t seem > to know how #hash should be implemented: > > Not sure what gives this impression, while learning algorithms I've implemented a couple different hash algorithms (granted the keys were always strings). > I usually just delegate to one of my attributes' hash methods (e.g. for a > > user, I might use its user's name's hash). I'm not sure what advantage > > would be gained by establishing a standard. > > If there was a standard way, then no one would have to ask if there > was one. That would change the answer, not the question. It would make implementing #hash, which you should/must do > if you implement #=3D=3D, trivial, as there=92s then only one way to do s= o. > Delegating to the most relevant attribute still seems more trivial. It would make hashing conflicts less likely, as the correct set of > parameters would be used, whatever the object, and a uniform > distribution could be established across different classes of objects. > > It still seems that delegating to an attribute like an id or a string which is likely unique, would yield sufficient uniqueness, and probably be more performant as it would require fewer calculations. You may be more likely to have a collision, but I'd expect that the likelihood of this is not increased much, and the benefit saved on calculations and on complexity of implementation would more than make up for it. I suppose one reason I take this view could be that the only viable scenarios I can think of for making some arbitrary object into a hash key are for sets and Array#uniq. For me, these scenarios are exceedingly rare, and have always been trivially replaced with alternative keys. --bcaec53f395b5bb33204b54c1211--