Ruby Tip2: Comparator For Comparing Objects

Vamsi Krishna

1 min read

In Ruby, we can compare two objects by several number of ways. But I want to compare a particular class instances only on one of its properties(that is attributes of a model).

For example lets take a class called Person
[source language=”ruby”]
class Person
attr_accessor :name,:age
If I compare two person classes, it would be logical to compare only age of the person instead of comparing on every attribute of the person class (this is the business logic I am using for comparing two person objects). You can write your own business logic for comparing two person objects.
Anyway I came across a code snippet which is kind of alien to me when I first looked at it. It looks like method overriding in ruby (not so sure whether it is overriding or not).
Let me share the code with you
[source language=”ruby”]
class Person
attr_accessor :name, :age
def initialize(name,age) = name
self.age = age
def <=> other_person
self.age <=> other_person.age
Anyway lets take two instances of person class:
[source language=”ruby”]
person1 =“vamsi”,23)
person2 =“alok”,22)
puts person1.<=> person2 # will print 1 (it will compare both objects based on only age)
# or you can simply call
person1 <=> person2
#As you know <=> operator returns 1,-1 or 0 based on the comparsion
If you want to extend this functionality to a bit more, you can include Comparable module in your class. Then you can use all new comparisons between objects
person1 < person2 # will print true
So the comparison is only based on the age attribute of person class.
This you can use it models or any classes. Anyway hope this tip is useful.
Please drop a comment if you have any further insights about this idea.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *