Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ruby equal方法总是返回参数值而不是返回值_Ruby - Fatal编程技术网

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)
,但请不要这样做。

请注意,对于赋值方法,在使用赋值语法时将忽略返回值。相反,将返回参数”