+ =的Ruby方法 [英] Ruby method for +=
本文介绍了+ =的Ruby方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有办法使Ruby能够执行类似的操作?
Is there a way to make Ruby able to do something like this?
class Plane
@moved = 0
@x = 0
def x+=(v) # this is error
@x += v
@moved += 1
end
def to_s
"moved #{@moved} times, current x is #{@x}"
end
end
plane = Plane.new
plane.x += 5
plane.x += 10
puts plane.to_s # moved 2 times, current x is 15
推荐答案
+=
运算符与任何方法都不相关,它只是语法糖,当您编写a += b
时,Ruby解释器将其转换为a = a + b
,对于转换为a.b = a.b + c
的a.b += c
也是一样.因此,您只需要根据需要定义方法x=
和x
:
The +=
operator is not associated to any method, it is just syntactic sugar, when you write a += b
the Ruby interpreter transform it to a = a + b
, the same is for a.b += c
that is transformed to a.b = a.b + c
. Thus you just have to define the methods x=
and x
as you need:
class Plane
def initialize
@moved = 0
@x = 0
end
attr_reader :x
def x=(x)
@x = x
@moved += 1
end
def to_s
"moved #{@moved} times, current x is #{@x}"
end
end
plane = Plane.new
plane.x += 5
plane.x += 10
puts plane.to_s
# => moved 2 times, current x is 15
这篇关于+ =的Ruby方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文