Hash return is not correct
Mon, 06 May 2013 00:20:24 -0700 Post Comments
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 => {
#<Router:0x10f80ae70 @model="3000", @make="Linksys">=>1,
#<Router:0x10f80ae20 @model="2000", @make="Linksys">=>1,
#<Router:0x10f80aec0 @model="2000", @make="Linksys">=>1,
#<Router:0x10f80add0 @model="3200", @make="Linksys">=>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.
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 => {
#<Router:0x10f80ae70 @model="3000", @make="Linksys">=>1,
#<Router:0x10f80ae20 @model="2000", @make="Linksys">=>1,
#<Router:0x10f80aec0 @model="2000", @make="Linksys">=>1,
#<Router:0x10f80add0 @model="3200", @make="Linksys">=>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.
