Phrogz
8/20/2007 3:10:00 PM
On Aug 20, 8:58 am, acmem...@yahoo.com wrote:
> I understand that the key of a hash can be any object. Therefore,
> I would think that the key of a hash can be another hash. If I have
> the following code sequence. (I using ruby 1.8.5 (2006-08-25) [i486-
> linux])
>
> require 'pp'
> test ={}
> test["new"=>"girl"]= 100
> test["new"=>"girl"]= 200
> pp test
>
> I am expecting the output to be
>
> {{"new"=>"girl"}=>200}
>
> However the output I am getting is
>
> {{"new"=>"girl"}=>100,
> {"new"=>"girl"}=>200}
>
> Could some explain how to use hash key which is of type hash
irb(main):001:0> h1 = {}
=> {}
irb(main):002:0> h2 = { :foo=>'bar' }
=> {:foo=>"bar"}
irb(main):003:0> h1[ h2 ] = 'hello'
=> "hello"
irb(main):004:0> h1[ h2 ] = 'world'
=> "world"
irb(main):005:0> h1
=> {{:foo=>"bar"}=>"world"}
irb(main):006:0> h1[ :a=>1 ] = 42
=> 42
irb(main):007:0> h1[ :a=>1 ] = 2000
=> 2000
irb(main):008:0> h1
=> {{:a=>1}=>2000, {:foo=>"bar"}=>"world", {:a=>1}=>42}
If it's TRULY the same hash, you get what you expected: the new value
overwrites the old.
What you did, and what you see on lines 6 and 7 above, is to create a
new hash on the fly that happens to have the same values as another
hash. To Ruby, those are treated as two different keys.