Array Manupulation

Can anyone help me on the following?

I have the following 2 arrays, how do i get c as a result of a and b. The elements should be in the specified order.

a = ["(modulable_type=?) AND (parent_id=?) AND (status=?)","Task","2","20"] b = ["(tasks.due_date=?)", "2009-08-22"]

c = ["(modulable_type=?) AND (parent_id=?) AND (status=?) AND (tasks.due_date=?)","Task","2","20","2009-08-22"]

Thanks and Regards, Pratik

Answer:

I have encountered exactly this problem and realised that, though this is solvable, it is better (if possible) to build the arrays differently in the first place. I realise this may not be possible for you but if you change the original conditions building so that it builds two arrays of the form conditions = ["(modulable_type=?)","(parent_id=?)"] and values = ["Task","2"] and so on, so just adding each condition and value as they arise, then the required result is c = [conditions.join(" AND ")] + values

No doubt there are even better ways, and it may not match your needs anyway, but for me it worked well as I was working through a number of options building the conditions as I went.

Colin

and b similarly Then c = (a+b).collect(

Doing things like this, it may be easier to use the named placeholders version - so your example will look like:

a = ["(modulable_type=:modulable_type) AND (parent_id=:parent_id) AND (status=:status)",{:modulable_type => "Task", :parent_id => "2", :status => "20"}] b = ["(tasks.due_date=:due_date)", {:due_date => "2009-08-22"}]

Then c is as simple as:

c = ["#{a[0]} AND #{b[0]}", a[1].merge(b[1])]

Note: this will fail in creative ways if you have parameters in a and b that are supposed to have different values but have the same name, so don't do that. :slight_smile:

--Matt Jones

Instead of doing funky array manipulation to build your model's SQL find conditions, are you absolutely sure you shouldn't just be using scopes instead?

pharrington wrote:

(tasks.due_date=?)","Task","2","20","2009-08-22"]

Thanks and Regards, Pratik

Instead of doing funky array manipulation to build your model's SQL find conditions, are you absolutely sure you shouldn't just be using scopes instead?

Or if not scopes, plain old conditions hashes. If you're trying to use this as a :conditions parameter to find, remember that :conditions will also take a hash:

["(modulable_type=?) AND (parent_id=?) AND (status=?) AND (tasks.due_date=?)","Task","2","20","2009-08-22"] {:modulable_type => 'Task', :parent_id => 2 ... } Best,