Last active
January 28, 2016 08:49
-
-
Save LolWalid/b009403d4e2850af537b to your computer and use it in GitHub Desktop.
Operator Overloading in ruby
This file contains hidden or 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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another usefull tip is to override spaceship operator to be able to sort an array of objects.