In theprevious 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:
classCarattr:speeddefinitialize(speed)@speed=speedendend
And now let’s make their instances comparable by including the Comparable module and defining the<=>
pseudooperator.
classCarincludeComparableattr:speeddef<=>(other)self.speed<=>other.speedenddefinitialize(speed)@speed=speedendendcar1=Car.new(100)car2=Car.new(120)car3=Car.new(90)pcar2>car1# truepcar3>car2# falsecars=[car1,car2,car3]pcars.sort()# [#<Car:0x000055aec8add4b0 @speed=90>, #<Car:0x000055aec8add500 @speed=100>, #<Car:0x000055aec8add4d8 @speed=120>]
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse