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

≯℡__Kan透↙ 提交于 2019-12-10 21:02:23

问题


It seems surprising that in all other instances irb will echo the return value of a method. Why does assignment via a setter behave differently?

I'm using 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

update

It has dawned on me that it echoes the rhs because that's the actual return value. Why is this?


回答1:


Following the @Matz reply in this thread :

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.




回答2:


Haven't found a concrete answer why, but this page as a discussion about it.

Specifically:

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.

Think about something like this, that many people would be used to seeing from other languages like C:

foo.x = foo.y = 3

You'd assume foo.x and foo.y were both set to 3, and because of this Ruby "feature", you'd be right.

edit: Arup's post has a good link to a why...



来源:https://stackoverflow.com/questions/30382543/why-does-irb-echo-the-right-hand-side-of-an-assignment-instead-of-the-return-val

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!