DEV Community

Avraam Mavridis
Avraam Mavridis

Posted on

2 2

CodeTip - Ruby: Compare class instances

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>]

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs