From: Stefano Crocco Date: 2007-09-18T00:48:45+09:00 Subject: Re: how to use tuple as hash key Alle luned狸 17 settembre 2007, SpringFlowers AutumnMoon ha scritto: > in Python, a hash key cannot be [1,2,3] but must be (1,2,3), a tuple. > > in Ruby, a list can actually be used as a hash key... but is it true > that it is using the list's ID as the key, not the list's content... > > (that's why in Python, tuples can be used as hash keys, since they are > unique by the values they contain) > > what about in Ruby, since there is no tuple, how can you similate using > tuple as hash key? using list.join(",") as a key? I think that ruby uses the content of the array, not its id: irb: 001> a=['a','b'] ["a", "b"] irb: 002> h = {a => 2} {["a", "b"]=>2} irb: 003> b = %w[a b] ["a", "b"] irb: 004> h[b] 2 irb: 005> a.object_id == b.object_id false If the object_id of the two arrays were used as hash keys, h[b] would have returned nil, since the two ids are different. You must be careful when using mutable objects as hash keys, since modifying the object will also modify the key, and requires to re-index the hash (using Hash#rehash). For example, referring to the previous irb session: irb: 010> a << 'c' ["a", "b", "c"] irb: 011> h[a] nil irb: 012> h[b] nil irb: 014> h.rehash {["a", "b", "c"]=>2} irb: 015> h[a] 2 I hope this helps Stefano