简体   繁体   English

Ruby将参数传递给方法

[英]Ruby pass arguments to a method

I would like to add a method to a class C 我想向C类添加方法

class C
end

I defined a proc: 我定义了一个过程:

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

I added the proc to the class as a method foo : 我将proc作为方法foo添加到了类中:

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

When I call foo as C.new.foo(1,2) , I get an error: 当我将foo称为C.new.foo(1,2) ,出现错误:

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

To avoid this, I need to call foo like C.new.foo([1,2]) . 为了避免这种情况,我需要像C.new.foo([1,2])一样调用foo Someone can tell me how to avoid this problem? 有人可以告诉我如何避免这个问题?

Answering the question stated: 回答问题:

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

Since you want to pass an arbitrary amount of parameters to the method, the lambda should receive splat argument. 由于要向该方法传递任意数量的参数,因此lambda应该接收splat参数。

Also, defaulting to impl.parameters.map(&:last) makes not much sense, since the defaults will be symbols [:x, :y] . 另外,默认为impl.parameters.map(&:last)没有太大意义,因为默认impl.parameters.map(&:last) 符号 [:x, :y]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM