简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM