18

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

1 回答 1

28

splatargs数组:send(real_method, *args)

于 2010-03-29T01:12:02.770 回答