Why Does def some_func=(obj) Behave This Way?

Hello Everyone,

Why does this function behave this way?

class Confuse

def confusion=(obj)
@obj = obj
return ‘expected answer’
end
end
c = Confuse.new

c.confusion = ‘this should be wrong’

This returns ‘this should be wrong’.

I am reading Programming Ruby 1.9 & 2.0 by Dave T. with Chad
Fowler
and Andy H… This problem was mentioned in page 129, but their
explanation did not really make sense.

On Mon, Jan 20, 2014 at 1:30 PM, Peter [email protected] wrote:

This returns ‘this should be wrong’.

Ruby setters always ignore your explicit return and the last line as a
return and return the attribute given it… as a feature, and this
should be expected behavior as all Ruby setters behave this way.

This means that you define :hello= and it accepts the attribute :world
and you give :world the value of “foo” it will return “foo” because
that was the value it was given for it’s assignment and logically that
is the value it should return if it returns anything at all. To
return “expected answer” would be ambiguous no matter how you try to
play it.