Separating an Array into a comma seperated string with quotes

Posted by user548744 on Stack Overflow See other posts from Stack Overflow or by user548744
Published on 2010-12-22T02:35:46Z Indexed on 2010/12/22 2:53 UTC
Read the original article Hit count: 237

Filed under:

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 seperated (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?
Thanks

© Stack Overflow or respective owner

Related posts about ruby-on-rails