In the previous post I wrote about how to compare objects in Javascript. In Ruby we can do the same using the Comparable module. We include the comparable module in our class and we define a pseudooperator-method <=>
. Let’s say we have again a Car class that looks like this:
class Car
attr :speed
def initialize(speed)
@speed = speed
end
end
And now let’s make their instances comparable by including the Comparable module and defining the <=>
pseudooperator.
class Car
include Comparable
attr :speed
def <=>(other)
self.speed <=> other.speed
end
def initialize(speed)
@speed = speed
end
end
car1 = Car.new(100)
car2 = Car.new(120)
car3 = Car.new(90)
p car2 > car1 # true
p car3 > car2 # false
cars = [car1, car2, car3]
p cars.sort() # [#<Car:0x000055aec8add4b0 @speed=90>, #<Car:0x000055aec8add500 @speed=100>, #<Car:0x000055aec8add4d8 @speed=120>]
Top comments (0)