From: Ruby Mania Date: 2013-05-07T02:22:44+09:00 Subject: Re: Hash return is not correct All, Thanks a lot ! Damm I forgot the simple concept of contract between eql and hashcode :D Again thanks !! Per-erik Martin wrote in post #1107918: > Ruby Mania wrote in post #1107907: >> >> def ==(other) >> return false unless other.is_a?(Router) >> make == other.make && model == other.model > > That should be eql?, and @make/@model: > > def eql?(other) > return false unless other.is_a?(Router) > @make.eql?(other.make) && @model.eql?(other.model) > end > > >> end >> > > You also need to override the hash method, e.g.: > > def hash() > @make.hash ^ @model.hash > end > > >> end >> >> frequency = Hash.new(0) >> models = %w(2000 3000 2000 3200) >> models.each{|m| frequency[Router.new('Linksys',m)] += 1} >> puts frequency[Car.new('Linksys','2000')] > > As noted, should be Router: > > puts frequency[Router.new('Linksys','2000')] -- Posted via http://www.ruby-forum.com/.