加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby – 调用方法传递数组的值作为每个参数

发布时间:2020-12-16 20:38:48 所属栏目:百科 来源:网络整理
导读:我目前坚持这个问题.我已经在我做过的类中加入了method_missing函数.当调用不存在的函数时,我想调用另一个我知道的函数存在,将args数组作为所有参数传递给第二个函数.有没有人知道这样做的方法?例如,我想做这样的事情: class Blah def valid_method(p1,p2,
我目前坚持这个问题.我已经在我做过的类中加入了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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读