ruby equal方法总是返回参数值而不是返回值
我的问题是在赋值时可以修改我的值,但是ruby equal方法总是返回参数值而不是返回值,ruby,Ruby,我的问题是在赋值时可以修改我的值,但是#bar=返回的值将不是我的隐式返回值,而是值参数 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 look
#bar=
返回的值将不是我的隐式返回值,而是值
参数
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"
我想在最后一行打印“这些不是你要找的机器人”
,而不是42
。可能吗
可能吗
不,这就是赋值运算符在ruby中的处理方式。您可以从bar=
切换到,比如说,set\u bar
。这现在只是一个普通方法,不会在赋值操作中忽略它的返回值(因为它不能在那里使用)
或者您可以执行类似于foo.send(“bar=”,42)
,但请不要这样做。请注意,对于赋值方法,在使用赋值语法时将忽略返回值。相反,将返回参数”