This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Point | |
attr_reader :x, :y | |
def initialize(x, y) | |
@x = x | |
@y = y | |
end | |
def ==(other) | |
@x == other.x && @y == other.y | |
end | |
def to_s | |
"(#{x}, #{y})" | |
end | |
def inspect | |
to_s | |
end | |
end | |
p [Point.new(1, 1), Point.new(2, 2), Point.new(3, 3)] - [Point.new(3, 3), Point.new(1, 1)] | |
# => [(1, 1), (2, 2), (3, 3)] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Point | |
attr_reader :x, :y | |
def initialize(x, y) | |
@x = x | |
@y = y | |
end | |
def ==(other) | |
eql?(other) | |
end | |
def eql?(other) | |
@x == other.x && @y == other.y | |
end | |
def hash | |
@x + @y | |
end | |
def to_s | |
"(#{x}, #{y})" | |
end | |
def inspect | |
to_s | |
end | |
end | |
p [Point.new(1, 1), Point.new(2, 2), Point.new(3, 3)] - [Point.new(3, 3), Point.new(1, 1)] | |
# => [(2, 2)] |
==
のオーバーライドだけでは足りず、eql?
とhash
のオーバーライドが必要だった。
0 件のコメント :
コメントを投稿