views:

56

answers:

1

Being still somewhat new to Ruby, I'm not sure how to do this... Let's say I have a method that takes a variable number of arguments:

def mytest(*args) puts args.to_json end

Obviously I can call it with whatever I like, such as:

mytest('one', 'two', 'three')

No problem. But what I need to do is call it with a dynamically-created set of arguments. For example, I'm pulling a result set from the database, and I don't know how many entries will come back. Let's say I want to collect the result ids, and call mytest() with them -- how would I construct the set of arguments to pass to mytest()?

This seems somehow obvious, but for whatever reason, it isn't. I realize that I could instead write mytest() to take an array or Hash, but I'm actually trying to call a method in a plugin that I didn't write.

+9  A: 

I'm not sure I understood your question. Are you asking how to turn an array into the arguments of a method? Read this

Let's say you have this:

a = [1,2,3,4]

and a method taking 4 parameters, like:

def whatever(p1,p2,p3,p4)
  # do whatever you want with them here
end

You can call the method, like this:

whatever(*a)

and the array's elements will be sent the way you want them to.

Geo
I think that's what he wants.
Trevoke
Yes, that's exactly it, thanks! For those of us coming from a background that includes C, that looks both odd and sensible, actually. The only other solution I'd come up with was to use eval() after building a String appropriately, but that's obviously Not Nice for a number of reasons.
Masonoise