【问题标题】:Ruby - Call method passing values of array as each parameterRuby - 调用方法将数组的值作为每个参数传递
【发布时间】:2011-02-01 21:07:28
【问题描述】:

我目前被困在这个问题上。我已经在我创建的一个类中加入了 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

(哦,顺便说一句,上面的例子对我不起作用)

编辑

根据提供的答案,这是有效的代码(上面的代码有错误):

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

【问题讨论】:

    标签: ruby arrays methods parameter-passing


    【解决方案1】:

    拆分args 数组:send(real_method, *args)

    【讨论】:

      猜你喜欢
      • 2010-10-24
      • 2014-04-09
      • 1970-01-01
      • 2016-11-02
      • 2010-10-06
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 2020-03-16
      相关资源
      最近更新 更多