Skip to content

Instantly share code, notes, and snippets.

@wallace
Created December 13, 2011 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wallace/1473203 to your computer and use it in GitHub Desktop.
Save wallace/1473203 to your computer and use it in GitHub Desktop.
Implementing Set Functionality (equality) in Ruby Classes
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