扩展Object类的发送方法

时间:2013-04-05 06:15:46

标签: ruby

我想在Ruby中更改send方法。我的代码如下

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)之类的send函数时,我收到了这个错误:

ArgumentError: wrong number of arguments (1 for 0)

错误发生在线路调用__ send__功能上。 那么我该如何解决这个错误。

2 个答案:

答案 0 :(得分:1)

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

__send__(symbol, *args)

答案 1 :(得分: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]