From: ara.t.howard@... Date: 2006-12-13T03:58:19+09:00 Subject: Re: Assignment method strangeness On Wed, 13 Dec 2006, Ryan Williams wrote: > Assignment methods are weird, and I wish they acted more like regular > methods. It seems like they could be, but the parser doesn't properly parse > the usage. Let me show you what I mean. > > Assignment methods can't take more than one argument: > > class Test > def d=(a,b) > puts "A: #{a}, B: #{b}" > end > end > > test.d = 1, 2 #=>ArgumentError: wrong number of arguments (1 for 2) > test.d = [1, 2] #=> ArgumentError: wrong number of arguments (1 for 2) > test.d = *[1, 2] #=> ArgumentError: wrong number of arguments (1 for 2) > > Assignment methods can't take blocks: > > class Test > def t=(t, &block) > @t = t > block.call > end > end > > test = Test.new > test.t = 5 { puts "block" } #=> SyntaxError: compile error > #=> parse error, unexpected '{', > expecting $ > > > You can't seem to replace the single required argument with a block: > > class Test > def v=(&block) > block.call > end > end > > test = Test.new > test.v ={ puts "block" } #=> Exception: wrong number of arguments (1 for > 0) > > > You can, of course, get around these restrictions with #send > > test.send(:d=, 1, 2) #=> A: 1, B: 2 > > Though you can define these methods all you want, it seems as though the > parser that does the syntactic sugaring at the call location makes some very > narrow assumptions about the nature of the assignment method. Is there any > way around this? > > -RYaN harp:~ > cat a.rb require 'rubygems' require 'attributes' class Test attribute 't' end test = Test.new test.t 42 p test.t harp:~ > ruby a.rb 42 it looks really nice with classes: harp:~ > cat a.rb require 'rubygems' require 'attributes' class Base class << self attribute 'a' => 4 attribute 'b' => 2 attribute 'c' # no default value end end class Derived < Base c 'forty-two' end p [Derived.a, Derived.b] p Derived.c harp:~ > ruby a.rb [4, 2] "forty-two" if you don't want to install the gem just download and cut and paste the code: it's on 42 lines long! -a -- if you find yourself slandering anybody, first imagine that your mouth is filled with excrement. it will break you of the habit quickly enough. - the dalai lama