5 ms·
It's related to the right-associativity of the assignment operator and its expected semantics. If you write a = b = c then it is interpreted as a = (
by grn 14y ago
It's related to the right-associativity of the assignment operator and its expected semantics. If you write
a = b = c
then it is interpreted as
a = (b = c)
When c = 5 then you expect that
a = b = 5 # which is equivalent to a = (b = 5)
results in a and b set to 5. That's why = must return its right-hand side.
- deleted 14y ago[deleted]
- Denzel 14y agoAgreed. I understand exactly what you're saying, and I don't dispute the semantics. I guess my only problem is that in this case "t.attr" isn't really equal to 5, therefore making a = t.attr = 5 differ from t.attr = 5 a = t.attr 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. :)
- chc 14y agoThe alternative is making a = t.attr = 5 different from t.attr = 5 a = 5 which is most often what someone means when they write a chained assignment. It's all part of the "principle of least surprise" that Rubyists used to tout so much — but unfortunately, different people find different things surprising.
- grn 14y agoPlease also note that t.send(:attr=, 5) returns 10. 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.