Ruby将参数传递给方法
我想给C类添加一个方法Ruby将参数传递给方法,ruby,Ruby,我想给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 ) 当我
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)
也没有多大意义,因为默认设置将是符号[:x,:y]
哈?你能不能定义一个“正常”的方法?你试过C.new.foo(1,2)吗?啊,当然。我还需要更多的咖啡:)不过,我的问题是,这种复杂性值得吗?用常规的方法,你不会有任何问题,只是说。你必须解释,你在那里试图做什么。特别是在lambda do | args=impl.parameters.map{| arg | arg[1]}
中,更简单的代码是:没有签名检查。不过,您可以在方法体中自由地实现它们。