Reno
Reno

Reputation: 2982

Separating an Array into a comma separated string with quotes

I'm manually building an SQL query where I'm using an Array in the params hash for an SQL IN statement, like: ("WHERE my_field IN('blue','green','red')"). So I need to take the contents of the array and output them into a string where each element is single quoted and comma separated (and with no ending comma).

So if the array was: my_array = ['blue','green','red']

I'd need a string that looked like: "'blue','green','red'"

I'm pretty new to Ruby/Rails but came up with something that worked:

if !params[:colors].nil?
   @categories_array = params[:colors][:categories]
   @categories_string =""
   for x in @categories_array
      @categories_string += "'" + x + "',"
   end
   @categories_string.chop!     #remove the last comma
end

So, I'm good but curious as to what a proper and more consise way of doing this would look like?

Upvotes: 4

Views: 8348

Answers (5)

Manavendra Singh
Manavendra Singh

Reputation: 305

Rails (actually ActiveSupport, part of the Rails framework) offers a very nice Array#to_sentence method.

If you are using Rails or ActiveSupport, you can call

['dog', 'cat', 'bird', 'monkey'].to_sentence # "dog, cat, bird, and monkey"

Upvotes: 0

Harish Shetty
Harish Shetty

Reputation: 64363

If you are using the parameter hash you don't have to do any thing special:

Model.all(:conditions => {:category => @categories_array})
# => SELECT * FROM models WHERE (category in ('foo', 'bar', 'baz'))

Upvotes: 0

Mark Thomas
Mark Thomas

Reputation: 37507

This functionality is built into ActiveRecord:

Model.where(:my_field => ['blue','green','red'])

Upvotes: 5

Jacob Relkin
Jacob Relkin

Reputation: 163228

Use map and join:

@categories_string = @categories_array.map {|element|
  "'#{element}'"
}.join(',')

Upvotes: 13

dnch
dnch

Reputation: 9605

Are you going to pass this string on to a ActiveRecord find method?

If so, ActiveRecord will handle this for you automatically:

categories_array = ['foo', 'bar', 'baz']
Model.find(:all, :conditions => ["category in (?)", categories_array])

# => SELECT * FROM models WHERE (category in ('foo', 'bar', 'baz'))

Hope this helps.

Upvotes: 5

Related Questions