David Vallner
12/3/2006 10:54:00 AM
paul wrote:
> Hi all,
> I thought it to be good programming style to make attribute assignment
> chainable. When using the attr_writer an assignment returns te value
> assigned which is not what I want, so I tried to do-it-myself.
> The result is below. This doesn't work. When running Ruby gives:
> undefined method 'b=' for "AA":String (NoMethodError)
> Anybody, please tell me: *why*. What simple stuppid thing am I
> overseeing?
> Thanks in advance!
> Cheers,
> Paul
>
> --the code--
> class A
> def initialize
> end
> def a
> return @a
> end
> def a=(someA)
> @a = someA
> return self
> end
> def b
> return @b
> end
> def b=(someB)
> @b = someB
> return self
> end
> end
>
> puts A.new.a=("AA").b=("BB").a
> --the code--
>
>
There is no bug in your code, apparently Ruby always returns the rvalue
from what parses as an assignment.
With your class loaded into irb, I got:
irb(main):039:0> A.new.a=("AA")
=> "AA"
irb(main):043:0> A.new.send('a=', 'AA') # Does what you expected.
=> #<A:0x3b3015c @a="AA">
So, can anyone recall a rationale for the behaviour (consistency with
mainstream programming languages with regards to assignment?) or is this
a Ruby bug?
Either way, disclaimer: I don't like what you're trying to do in the
first place. Pretty much anyone reading your code will expect assignment
to return the rvalue because that's what #attr_writer does, and the
chained assignment in your example just reads plain ugly to me,
especially since I subconsciously parse it as:
A.new.a = "AA".b = "BB".a
i.e. ``assign "BB".a to -both- "AA".b and A.new.a''
and therefore am in favour of consistency with assignment in other
languages instead of consistency with Javaesque property setters (where
the ambiguity doesn't manifest.)
David Vallner