3章 その8 hashのkeyに配列を使う

p.39のhcluster関数の

distances = {}
if(clust[i].id,clust[j].id) not in distances:
  distances[(clust[i].id,clust[j].id)] = distance(clust[i].vec,clust[j].vec)

がいまいちわからなかったんだけど、よく見たらリストをキーにとるディクショナリ(ハッシュ)を使っていた。
今までhashのkeyはstringだと思ってたのでびっくり。たぶんどんなオブジェクトでもkeyにできるみたい


リストをキーにするディクショナリ

Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> h = {}
>>> h["a"] = 1
>>> h["a"]
1
>>> h[(5,6)] = 2
>>> h[(5,6)]
2
>>> h
{'a': 1, (5, 6): 2}


rubyではどうか。
irbで、配列をキーにするHashを作ってみる

>> h = Hash.new
=> {}
>> h["a"] = 1
=> 1
>> h["a"]
=> 1
>> h[[5,6]] = 2
=> 2
>> h[[5,6]]
=> 2
>> h
=> {"a"=>1, [5, 6]=>2}
>> h.keys
=> ["a", [5, 6]]

普通にできるね