3

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?

2 Answers2

5

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.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
4

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...

Nick Veys
  • 23,458
  • 4
  • 47
  • 64