2017-04-16 183 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]