为什么 irb 在 setter 方法的情况下回显赋值的右侧而不是 return 值?

Why does irb echo the right hand side of an assignment instead of the return value in the case of a setter method?

令人惊讶的是,在所有其他情况下,irb 都会回显方法的 return 值。为什么通过 setter 进行赋值会有所不同?

我正在使用 Ruby 2.2.2.

irb(main):001:0> def x=(value); puts "puts_from_x"; "returned_string_from_x"; end
=> nil

irb(main):002:0> self.x = 3
puts_from_x
=> 3

更新

我突然意识到它与 rhs 相呼应,因为那是 实际 return 值 。这是为什么?

在此 thread 中关注 @Matz 回复:

Setters always return the value they were originally assigned It's a design choice. We defined the value of the assignment as the value of the right hand expression, not the return value from the assigning method.

尚未找到具体答案,but this page as a discussion about it

具体来说:

If you define an « assignment-like » method (with an equal sign at the end), Ruby will execute the method when you call it, but will always return the supplied parameter and never the result of the method.

想一想这样的事情,很多人会习惯于从 C:

等其他语言中看到
foo.x = foo.y = 3

您假设 foo.xfoo.y 都设置为 3,因此 Ruby "feature",您是对的.

编辑:Arup 的 post 有一个很好的 link 原因...