paul wrote:
The new rule, written into my brain: methodes
whose names end in '='
Read: assignments.
always return the first argument.
As assignments do.
Don't think about attribute writes as methods. Don't write them as
methods, it just looks ugly and confuses people, apparently including
you ;
Writing this
down made me think: with multiple arguments, does it return them all,
or just the first. I gave it a try, and it seems like I'm not allowed
to give more then one argument to an methodes whose names end in '='.
That's because you're not calling the method per se. You're doing an
attribute write. The Ruby parser reads it as an assignment. The rvalue
isn't even being suspected of being a parenthetised argument list.
In your code, xx.x=('y', 'z') probably gets parsed as:
xx.x = ('y', 'z'),
where the assignment rvalue ('y', 'z') is invalid Ruby.
You're not allowed to have attribute setters take two parameters,
because it's a syntax feature to set a value to an attribute.
Just as a variable always points to -one- object, an attribute points to
one object as well.
Methods with identifiers ending in = are a special case. They're a
special case for (what I think are) good reasons, and it makes precious
little sense whatsoever to try to use them outside the context of that
special case - such use would be nonidiomatic, and confusing. Most
people reading your code using attribute setters as chained calls would
first cringe, then run it through a code beautifier to at least put a
space around the =, and then visually parse it in the completely wrong
way (as an assignment) if they acted as regular method calls.
Can anyone confirm this as a rule?
[snip code - speaking of which, please indent irb snippets too]
Also:
irb(main):001:0> class Foo
irb(main):002:1> def bar=(baz, bat)
irb(main):003:2> puts "Foo#bar= called with arguments baz=#{baz} and
bat=#{Bat}"
irb(main):004:2> return 'bing'
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0>
irb(main):008:0* foo = Foo.new
=> #<Foo:0x5bf151c>
irb(main):009:0> foo.bar = 1, 2
ArgumentError: wrong number of arguments (1 for 2)
from (irb):9:in `bar='
from (irb):9
Multiple items as the rvalue of an assignment expression are always
packed into an array as varargs:
C:\Documents and Settings\David>irb
irb(main):001:0> class Foo
irb(main):002:1> def bar=(baz)
irb(main):003:2> puts "Foo#bar= called with baz=#{baz.inspect}
irb(main):004:2> return :bing
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> Foo.new.bar = 1, 2
Foo#bar= called with baz=[1, 2]
=> [1, 2]
David Vallner
···
from :0