2017-04-16 66 views
0

我想的方法添加到C类红宝石传递参数的方法

class C 
end 

我定义一个PROC:

impl = proc{|x,y| puts "x=#{x} - y=#{y}"} 

我添加PROC到类作为方法foo

C.send(:define_method, :foo, lambda do |args = impl.parameters.map { |arg| arg[1] }| 
     puts "foo is called" 
     impl.call(args) 
    end 
) 

当我打电话fooC.new.foo(1,2),我得到一个错误:

ArgumentError: wrong number of arguments (2 for 0..1) 

为了避免这种情况,我需要调用fooC.new.foo([1,2])。有人可以告诉我如何避免这个问题?

+0

咦?你能否定义一个“正常”的方法? –

+0

您是否尝试过C.new.foo(1,2)? – Kagelmacher

+0

啊,当然。我需要更多的咖啡:)不过,我的问题是,这种复杂性是否值得?用常规方法你不会有任何问题,只是说。 –

回答

0

回答说这个问题:

C.send(:define_method, :foo, lambda do |*args| 
    args = impl.parameters.map(&:last) if args.empty? 
    puts "foo is called, args are: #{args.inspect}" 
    impl.call(*args) 
end) 
C.new.foo(1,2) 
#⇒ foo is called, args are: [1, 2] 
# x=1 - y=2 

既然你要的参数任意量传递到方法,该lambda应该得到图示的说法。

此外,默认为impl.parameters.map(&:last)没有多大意义,因为默认值为符号[:x, :y]