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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more