2
Ruby는 타입이 지정되지 않은 언어이므로 루비는 오히려 동성애입니다. 예 :Ruby 다른 유형의 객체에 대한 멤버십 설정
class Test
attr_reader :field
def initialize(f)
@field = String(f)
end
def ==(other)
field == String(other)
end
def eql?(other)
field.eql? String(other)
end
def hash
field.hash
end
def to_s
field
end
end
s = Set.new([Test.new('string')])
# => [#<Test:0x007fc97da17ea0 @field="string">]
puts Test.new('string').eql?(Test.new('string'))
# true
puts Test.new('string').hash == Test.new('string').hash
# true
puts s.member? Test.new('string')
# true
puts s.member? Test.new('other')
# false
puts Test.new('string') == 'string'
# true
puts Test.new('string').eql? 'string'
# true
puts Test.new('string').hash == 'string'.hash
# true
그러나, 루비 내부 검사를 몇 가지 유형을 적용처럼
puts s.member? 'string'
# false
이 보인다. 이게 사실인가요?
덜 침략적 인 패치에 대해 유형 검사 ('other.is_a? Test')를 추가 할 수 있습니다. – Stefan
작동하는 것 : http://ideone.com/7fibfL – Stefan
아마도 모듈로 메소드를 옮기고'refine' 또는'prepend'를 사용하여 적절한'super' 메소드를 사용합니다. 그런 다음 비교를 'other'(역순)로 위임하거나 'super'를 호출 할 수 있습니다. 즉, 'other.is_a? (Test)? 다른 사람 .eql? (self) : super' – Stefan