Pending Pending - 1 month ago 6
Ruby Question

How to add two objects of the same class in Ruby?

How do I override the + method in the class to add another object of the same class?

below is what I want to do but I'm sure my syntax is wrong

class Obj
def initialize( value )
@value = value
end

def +( obj_to_add )
@value +( obj_to_add.value )
end
end

o1 = Obj.new( 1 )
o2 = Obj.new( 1 )

puts o1 + o2

Answer

Your main problem with the above code is that you don't have an accessor for value which you require in your implementation of +.

Also it would potentially make more sense to return a new instance of the same class:

class Obj
  attr_reader :value

  def initialize(value)
    @value = value 
  end

  def +(other)
    self.class.new(@value + other.value)
  end
end

Obj.new(1) + Obj.new(2)
#=> #<Obj:0x007fa9138e0d28 @value=3>