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