Skip to content

Instantly share code, notes, and snippets.

@LolWalid
Last active January 28, 2016 08:49
Show Gist options
  • Save LolWalid/b009403d4e2850af537b to your computer and use it in GitHub Desktop.
Save LolWalid/b009403d4e2850af537b to your computer and use it in GitHub Desktop.
Operator Overloading in ruby
class CustomObject
attr_reader :a, :b
def initialize(a, b)
@a = a
@b = b
end
def ==(other)
(@a + other.a) == (@b + other.b)
end
def +(other)
if other.class == self.class
return CustomObject.new(@a + other.a, @b + other.b)
elsif other.class == 1.class
@a += other
@b -+ other
self
end
end
end
object1 = CustomObject.new(2, 3)
object2 = CustomObject.new(4, 3)
object1 == object2 # true
object1 == object1 # false
object3 = object1 + object2 # create new object
object3 + 1
# point_2d.rb
class Point2D
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def ==(other)
(@x - other.x) == 0 && (@y - other.y) == 0
end
def +(other)
Point2D.new(@x + other.x, @y + other.y)
end
end
p1 = Point2D.new(1, 1)
p2 = Point2D.new(1, 1)
p1 == p2
p1 + p2
@yannvery
Copy link

Another usefull tip is to override spaceship operator to be able to sort an array of objects.

def CustomObject
#...
  def <=>(other)
    return nil unless other.is_a?(self.class)
    other.a <=> @a
  end

end

object1 = CustomObject.new(2, 3)
object2 = CustomObject.new(4, 3)
object3 = object1 + object2

[object1, object2, object3].sort
# => [
#          [0] #<CustomObject:0x007f92ae511600 @a=6, @b=6>,
#          [1] #<CustomObject:0x007f92ae579bb0 @a=4, @b=3>,
#          [2] #<CustomObject:0x007f92ae599ed8 @a=2, @b=3>
#      ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment