From: Edoardo Rossi Date: 2013-05-06T16:48:48+09:00 Subject: Re: Hash return is not correct On Mon, May 6, 2013 at 9:19 AM, Peter Hickman wrote: > No the output is correct. Your mistake is assuming that Router.new will > return the same object for the same input parameters. For example: > > frequency = Hash.new(0) > models = %w(2000 3000 2000 3200) > models.each{|m| frequency[Router.new('Linksys',m)] += 1} > > > p frequency => { > > #=>1, > > #=>1, > > #=>1, > > #=>1 > > } > > > Note each entry is a different object. This is the normal and correct > behaviour. When you do: > > puts frequency[Router.new('Linksys','2000')] > > I assume you meant this and not Car.new it creates yet another object which > of course is not in the hash and so returns 0. > > Maybe the example in the Hash docs could be useful to the OP: http://ruby-doc.org/core-2.0/Hash.html Quoting: " Hash Keys Two objects refer to the same hash key when their hash value is identical and the two objects are eql? to each other. A user-defined class may be used as a hash key if the hash and eql? methods are overridden to provide meaningful behavior. By default, separate instances refer to separate hash keys. A typical implementation of hash is based on the object’s data while eql? is usually aliased to the overridden == method: (...) " I hope this helps. e.