Ruby-调用将数组值作为每个参数传递的方法
我现在被困在这个问题上。在我创建的一个类中,我已经钩住了缺少函数的方法。当调用一个不存在的函数时,我想调用另一个已知存在的函数,将args数组作为所有参数传递给第二个函数。有人知道怎么做吗?例如,我想这样做:Ruby-调用将数组值作为每个参数传递的方法,ruby,arrays,methods,parameter-passing,Ruby,Arrays,Methods,Parameter Passing,我现在被困在这个问题上。在我创建的一个类中,我已经钩住了缺少函数的方法。当调用一个不存在的函数时,我想调用另一个已知存在的函数,将args数组作为所有参数传递给第二个函数。有人知道怎么做吗?例如,我想这样做: class Blah def valid_method(p1, p2, p3, opt=false) puts "p1: #{p1}, p2: #{p2}, p3: #{p3}, opt: #{opt.inspect}" end def metho
class Blah
def valid_method(p1, p2, p3, opt=false)
puts "p1: #{p1}, p2: #{p2}, p3: #{p3}, opt: #{opt.inspect}"
end
def method_missing(methodname, *args)
if methodname.to_s =~ /_with_opt$/
real_method = methodname.to_s.gsub(/_with_opt$/, '')
send(real_method, args) # <-- this is the problem
end
end
end
b = Blah.new
b.valid_method(1,2,3) # output: p1: 1, p2: 2, p3: 3, opt: false
b.valid_method_with_opt(2,3,4) # output: p1: 2, p2: 3, p3: 4, opt: true
class废话
def有效_方法(p1、p2、p3、opt=false)
放置“p1:#{p1},p2:#{p2},p3:#{p3},opt:#{opt.inspect}”
结束
缺少def方法(方法名,*args)
如果methodname.to\u s=~/\u带\u opt$/
real_method=methodname.to_s.gsub(/_,带_opt$/,'')
send(real_方法,args)#splat在args
array:send(real_方法,*args)
class Blah
def valid_method(p1, p2, p3, opt=false)
puts "p1: #{p1}, p2: #{p2}, p3: #{p3}, opt: #{opt.inspect}"
end
def method_missing(methodname, *args)
if methodname.to_s =~ /_with_opt$/
real_method = methodname.to_s.gsub(/_with_opt$/, '')
args << true
send(real_method, *args) # <-- this is the problem
end
end
end
b = Blah.new
b.valid_method(1,2,3) # output: p1: 1, p2: 2, p3: 3, opt: false
b.valid_method_with_opt(2,3,4) # output: p1: 2, p2: 3, p3: 4, opt: true