Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Call method passing values of array as each parameter

I'm currently stuck on this problem. I've hooked into the method_missing function in a class I've made. When a function is called that doesn't exist, I want to call another function I know exists, passing the args array as all of the parameters to the second function. Does anyone know a way to do this? For example, I'd like to do something like this:

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

(Oh, and btw, the above example doesn't work for me)

EDIT

This is the code that works, based on the answer provided (there's a mistake in the code above):

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
like image 280
Markus Orreilly Avatar asked Mar 29 '10 01:03

Markus Orreilly


1 Answers

splat the args array: send(real_method, *args)

like image 199
horseyguy Avatar answered Nov 14 '22 15:11

horseyguy