简体   繁体   English

如何在Ruby中添加相同类的两个对象?

[英]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 + . 上面代码的主要问题是,您没有实现+所需的value访问器。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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