我的问题是在赋值时可以修改我的值,但#bar=
返回的值不会是我的隐式返回值,而是value
参数。
class Foo
def bar=(value)
@bar = "these not the droids you are looking for"
end
def bar
@bar
end
end
foo = Foo.new
puts foo.bar = 42 # 42
puts foo.bar # "these not the droids you are looking for"
我希望我的最后一行打印"these not the droids you are looking for"
而不是42
.这可能吗?
这可能吗?
不,这就是在 ruby 中处理赋值运算符的方式。您可以从bar=
切换到,例如,set_bar
。现在这只是一个普通的方法,不会在赋值操作中忽略其返回值(因为它不能在那里使用)。
或者你可以做一些类似foo.send("bar=", 42)
的事情,但请不要这样做。