Why does irb echo to the right of the assignment instead of the return value in the case of the setter method?

It seems surprising that in all other cases irb will display the return value of the method. Why does assignment through a setter behave differently?

I am 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 dawned on me that it echoes rhs because that is the actual return value. Why is this?

+3


source to share


2 answers


Following @Matz's answer on this thread :



Setters always return the value they were originally assigned. This is a design choice. We have defined the assignment value as the right-hand expression value, not the return value from the assigning method.

+5


source


Didn't find a specific answer why but this page is like a discussion about it .

In particular:

If you define an "assignment" method (with an equal character at the end), Ruby will execute that method when it is called, but it will always return the supplied parameter and never be the result of the method.

Think of something like this that many people will get used to seeing other languages ​​like C:



foo.x = foo.y = 3

      

Let's assume foo.x

and are foo.y

set to a value 3

and because of this Ruby feature you are correct.

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

+4


source







All Articles