22532 次
2 に答える
76
Ruby==
では、 は単なるメソッド (上に構文シュガーがあり、foo == bar
の代わりに記述できるようになっています) であり、他のメソッドと同じようにfoo.==(bar)
オーバーライドします。==
class MyClass
def ==(other_object)
# return true if self is equal to other_object, false otherwise
end
end
于 2012-06-25T09:43:06.940 に答える
1
上記のように、==
は Ruby のメソッドであり、オーバーライドできます。メソッドでカスタム等価条件をコーディングします。例えば:
class Person
attr_reader :name, :gender, :social_id
attr_accessor :age
def initialize(name, age, gender, social_id)
self.name = name
self.age = age.to_i
self.gender = gender
self.social_id = social_id
end
def ==(other)
social_id == other.social_id
end
end
もう他のメソッドをオーバーライドする必要はありません。
于 2020-07-09T14:31:39.570 に答える