[英]Ruby pass arguments to a method
我想向C类添加方法
class C
end
我定义了一个过程:
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
)
当我将foo
称为C.new.foo(1,2)
,出现错误:
ArgumentError: wrong number of arguments (2 for 0..1)
为了避免这种情况,我需要像C.new.foo([1,2])
一样调用foo
。 有人可以告诉我如何避免这个问题?
回答问题:
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
应该接收splat参数。
另外,默认为impl.parameters.map(&:last)
没有太大意义,因为默认impl.parameters.map(&:last)
符号 [:x, :y]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.