Home > Net >  How to make equal objects on ruby?
How to make equal objects on ruby?

Time:07-08

The challenge is to make a class that build equals objects for the same value for example:

class Person

att_reader :name

def initialize(name)
@name = name
end
end

I want to make

p1 = Person.new('joe')
p2 = Person.new('joe')
p3 = Person.new('mary')

p1 == p2 #true
p2 == p3 #false

I already tried to look for singleton but I can't make method new to be private

CodePudding user response:

Let's use Comparable mixin

class Person
  include Comparable
  
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def <=>(other)
    name <=> other.name
  end
end
  • Related