Expanding an array parameter?

Hi everyone,

I am wondering if there is a way to pass a function an array, but have
it treated as if it was expanded.

Here is an example of what I am trying to do:

query_string = “param1 = ? AND param2 = ?”
parameters = [1,“test”]

Thing.find :all, :conditions => [query_string, parameters]

Is there a way to do something like this? A way to have the parameters
variable treated like an expanded array?

Thank you for your time,

JD

<…>

Thing.find :all, :conditions => [query_string, parameters]

Is there a way to do something like this? A way to have the parameters
variable treated like an expanded array?
<…>

You can expand array to values using * (splat).

Try: Thing.find :all, :conditions => [query_string, *parameters]

Regards,
Rimantas

http://rimantas.com/

Jackdan wrote:

query_string = “param1 = ? AND param2 = ?”
parameters = [1,“test”]

Thing.find :all, :conditions => [query_string, parameters]

The second value of the conditions array should either be a hash or some
replacement parameter value**. What you have right now has an array:

[“param1 = ? AND param2 = ?”, [1,“test”]]

but what you really want is:

[“param1 = ? AND param2 = ?”, 1, “test”]

which can be achieved by adding two arrays:

:conditions => [query_string] + [parameters]

You could alternatively build a hash with named parameters:

query_string = “param1 = :p1 AND param2 = :p2”
parameters = {:p1 => 1, :p2 => “test”}

:conditions => [query_string, parameters]

**Side Note: The second and subsequent values in the conditions array
can be arrays which can be used like so:

Thing.find :all, :conditions => [‘id in(?)’, [1,2,3,4]]

Rimantas L. wrote:

You can expand array to values using * (splat).

Lovely. There’s always an easier way! Thanks, Rimantas.