[英]How to add two objects of the same class in Ruby?
如何覆蓋類中的+方法以添加同一類的另一個對象?
以下是我想做的,但是我確定我的語法錯誤
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
上面代碼的主要問題是,您沒有實現+
所需的value
訪問器。
同樣,返回相同類的新實例可能更有意義:
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.