hakeの日記

Windows環境でプログラミングの勉強をしています。

Hashのkeyの等しさの判定

Rubyの勉強
Hashのkeyに独自クラスを使用した場合に、そのクラスのhash値が等しくて、かつ、#eql?がtrueならば、二つのkeyは等しいものと判断される。
以下で#hashの戻り値が@aであったり、#eql?がfalseであれば、#include?の結果はfalseになる。

class Test
  def initialize(val)
    @a = val
  end
  def hash
    100
  end
  def eql?(other)
    true
  end
end

hash = Hash.new
hash[Test.new(123)] = "123"
a = Test.new(456)

p hash.include?(a) #=> true