我真搞不清楚在Ruby中的分配方法。在文档中,它说:困惑在Ruby中的分配方法(定义法等号)
以等号结尾的方法表示分配方法。 对于分配方法,返回值被忽略,并且参数 的,而不是返回。
我知道这可能是用作类setter方法。不过,我仍然对这个概念感到困惑。在下面的代码中:
class Foo
# setter method
def foo=(x)
puts "OK: x=#{x}"
end
end
f = Foo.new
f.foo = 123 # OK: x=123
def a=(value)
puts "value is #{value}"
end
a = 123 # why there is no output?
p a # 123, why this only return the argument?
p a = 123 # 123, why this only return the argument?
为什么等号方法在类中和类外运行方式不同?