Created
December 13, 2011 18:22
-
-
Save wallace/1473203 to your computer and use it in GitHub Desktop.
Implementing Set Functionality (equality) in Ruby Classes
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
require 'set' | |
# Here's our simple point class that contains two integers, x and y | |
class Point | |
attr_accessor :x, :y | |
def initialize(x,y) | |
@x, @y = x, y | |
end | |
def eql?(other) | |
other.is_a?(Point) && | |
[x,y] == [other.x, other.y] | |
end | |
def hash | |
[x,y].hash | |
end | |
end | |
p1 = Point.new(1,1) | |
p2 = Point.new(1,1) | |
p3 = Point.new(0,1) | |
puts p1 == p2 # false | |
puts p1.eql?(p2) # true | |
points = [p1, p2, p3] | |
points.each {|e| | |
p e.hash # 13, 13, 9 | |
} | |
# NOTE: your memory locations will vary | |
puts Set.new(points).inspect # #<Set: {#<Point:0x103573880 @x=1, @y=1>, #<Point:0x1035735b0 @x=0, @y=1>}> | |
puts points.uniq.inspect # [#<Point:0x103573880 @x=1, @y=1>, #<Point:0x1035735b0 @x=0, @y=1>] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment