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.
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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.