0

我想更改 Ruby 中的发送方法。我的代码如下

class A
  def send(symbol, *args)
     #customize code here
     #finally call the orinial __send__ function
     __send__(symbol, args)
  end
end

但是,当我调用 obj.send('a_var=', 10) 等发送函数时,我得到了这个错误:

ArgumentError: wrong number of arguments (1 for 0)

错误在于调用 __ send__ 函数的行。那么我该如何解决这个错误。

4

2 回答 2

1

如果您想将调用作为单独的参数而不是数组传递*args给调用,您还需要在那里解构它:__send__

__send__(symbol, *args)
于 2013-04-05T06:30:46.303 回答
1

对我来说,你的代码没问题:

class A
  def send(symbol, *args)
     #customize code here
     #finally call the orinial __send__ function
     p 'this method has been called'
     __send__(symbol, args)
  end
  def show=(m)
   p m
  end

end

A.new.send('show=',1,3,4)
A.new.send('show=',1)
A.new.send(:show=,1)

输出:

"this method has been called"
[1, 3, 4]
"this method has been called"
[1]
"this method has been called"
[1]
于 2013-04-05T06:45:51.710 回答