我真搞不清楚在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?
爲什麼等號方法在類中和類外運行方式不同?