-
Notifications
You must be signed in to change notification settings - Fork 312
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
hash メソッドが載っていないクラスがある #2556
Comments
結論からいうと、載ってなくていいように思います。 ただ、 るりまの Object#hash の項目による確認Object#hash (Ruby 3.0.0 リファレンスマニュアル)
この引用にはまだPRが反映されてなく 仮にRubyユーザーが再定義したとしても内部で定義された関数が呼ばれ、ユーザーが独自に再定義する意味も特別なさそうです。 methodメソッドによる確認
p 1.method(:hash) # => #<Method: Integer(Kernel)#hash()>
p :sym.method(:hash) # => #<Method: Symbol(Kernel)#hash()>
p (1.0).method(:hash) # => #<Method: Float#hash()>
p [].method(:hash) # => #<Method: Array#hash()> |
Integer,Symbol は特別なので書くべきだと思います。 |
ちなみに RDoc には 逆に |
自分で引用しておきながらよく読めてなかったですが、 p "".method(:hash) # => #<Method: String#hash()> IntegerやSymbolでのhashの項目・説明についてここは、自分の意見の補強です。 う〜ん、再定義もされてない継承してるだけのメソッドは、基本的にそのクラスのインスタンスメソッドとして説明があるわけではないし、(再定義も含んで)定義されているかどうかでメソッドの説明を載せるかどうかになっていると、わかりやすい線引でよさそうと思っていました(実際のるりまは、ここに例外もありますが)。 しかし、 NumericでのObject#hashについて以下の観点から、
もしすべてのクラスに |
すみません、ここで言う『特別なので』とはどういう事を指しているのでしょうか。 |
自分が「特別」の意味で使っていたのは、るりまの Object#hash (Ruby 3.0.0 リファレンスマニュアル)
具体的には一般的なクラスの場合具体的には、普通、一般的なクラスだと、 class Foo end
p({ Foo.new => 1, Foo.new => 2 }) # => {#<Foo:0x00000000011d5118>=>1, #<Foo:0x00000000011d50c8>=>2}
p([Foo.new, Foo.new].uniq) # => [#<Foo:0x00000000011d4bc8>, #<Foo:0x00000000011d4ba0>]
#再定義しなおすと、同一なものと判定するように変更できる
class Foo
def eql?(obj); true end
def hash; 0 end
end
p({ Foo.new => 1, Foo.new => 2 }) # => {#<Foo:0x00000000026991a8>=>2}
p([Foo.new, Foo.new].uniq) # => [#<Foo:0x0000000002698d20>] Integer, Symbol, Stringの特別なクラスの場合class Integer
def eql?(obj); raise end
def hash; raise ;end
end
p({ 1 => 1, 2 => 2 }) # => {1=>1, 2=>2}
p([1, 2].uniq) # => [1, 2]
|
https://github.com/ruby/ruby/blob/121fa24a3451b45c41ac0a661b64e9fc8600e589/hash.c#L191-L231 https://github.com/ruby/ruby/blob/fb04c69418ceee696a114fe31279cf3a5ea16d30/array.c#L5115 |
Numeric,Integer,Symbol などには
hash
メソッドが載っていません。(Float,String,Array などには載っています)
The text was updated successfully, but these errors were encountered: