Benjamin Paul Kay
4/30/2007 3:01:00 AM
On Thursday 30 May 2002, Jeff Gray wrote:
> We all know that one can either define a method that has a name of the form
> 'method=' (or use attr_accessor/attr_writer), and when Ruby sees
>
> obj.method = value
>
> the equivalent of
>
> obj.method=(value)
>
> I'm finding that the parser never expects or allows more than one argument
> to the 'method=' style of method naming. For example, you could define a
> method interface of:
>
> def method=(arg, &block)
>
> but the parser doesn't want to let you pass in a block to this call. Both
> of the following generate parse errors:
>
> obj.method = 12 { <some_code_here> }
> obj.method=(12) { <some_code_here> }
>
> (Simply removing the '=' from the method name allows the second case to
> work.) I couldn't find anything in the pickaxe book or in ruby-talk
> archives about this restriction. I'm on Ruby version 1.6.5 -- has this
> behavior changed in later versions, or is it a permanent trait of Ruby
> syntax?
>
> Thanks,
>
> - jeff
Also consider the test case below, where a method with = in its name always returns the value passed to it. This is really frustrating, as I want to use = in method names as syntactic sugar but can't because the methods don't behave like they're supposed to.
Is this a bug or a "feature"?
This script:
class TestClass
def test=(number)
# 42 is the answer to life the universe and everything.
42
end
def test(number)
# 42 is the answer to life the universe and everything.
42
end
end
test = TestClass.new
puts 'With the = in the method name:'
puts test.test=7
puts test.test=("Doesn't work with parentheses either.")
puts test.test=[1,2,3,"Arrays are cool!"]
puts 'And without:'
puts test.test(7)
puts test.test("Doesn't work with parentheses either.")
puts test.test([1,2,3,"Arrays are cool!"])
Produces output:
With the = in the method name:
7
Doesn't work with parentheses either.
1
2
3
Arrays are cool!
And without:
42
42
42