Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Ruby – 调用方法传递数组的值作为每个参数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我目前坚持这个问题.我已经在我做过的类中加入了method_missing函数.当调用不存在的函数时,我想调用另一个我知道的函数存在,将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$/,'')
            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

(哦,和btw,上面的例子不适合我)

编辑

这是基于提供的答案的代码(上面的代码中有一个错误):

class Blah
    def valid_method(p1,'')
            args << true
            send(real_method,*args) # <-- this is the problem
        end
    end
end

b = Blah.new
b.valid_method(1,opt: true

解决方法

splat的args数组:send(real_method,* args)

大佬总结

以上是大佬教程为你收集整理的Ruby – 调用方法传递数组的值作为每个参数全部内容,希望文章能够帮你解决Ruby – 调用方法传递数组的值作为每个参数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。