Are you an advanced rubyist?
Try to do this by memory without using a ruby interpreter.
Given:
class Test
def attr
@attr
end
def attr=(value)
@attr = value * 2
end
end
Evaluate: t = Test.new
t.attr = 5 # Returns => ?
t.attr # Returns => ?
I don't consider myself an advanced rubyist, and I couldn't answer this until today. Nonetheless, the behavior surprised me. I've read a number of books about ruby and never seen this behavior mentioned; in fact, most deem a setter method as just another method. Any explanation for this behavior?
9 comments
[ 3.5 ms ] story [ 34.7 ms ] threadI guess my only problem is that in this case "t.attr" isn't really equal to 5, therefore making
differ from which to a novice would appear equivalent. 99.9% of the time you wouldn't expect assignment to have side-effects. But in my eyes Ruby gives you so much power to use responsibly, it appears out of character to disallow it in this instance. (Note: I had to forgo a little trick with ActiveRecord that would've reduced duplication because of this.)In the grand scheme of things, it's not a big deal. But it was very interesting to me. :)
When you do t.attr = x Ruby sends :attr= with x as the argument to t and then ignores the return value of the message and returns x instead.
If you went directly through the method (e.g. `t.send(:attr=, 5)` or `t.method(:attr=).call 5`), you'd get 10.