Splitting an array into a comma-separated string with quotation marks

I manually create an SQL query in which I use Array in the params hash for the SQL IN statement, for example: ("WHERE my_field IN (" blue "," green "," red ")", So I need to take the contents of the array and print it to a line where each element is single and separated by a comma (and without a trailing comma).

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

I need a line that looks like this: "'blue','green','red'"

I'm 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 fine, but curious what the correct and more consistent way to do this would look like.

+3
source share
5 answers

ActiveRecord:

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

map join:

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

ActiveRecord?

, ActiveRecord :

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

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

, .

+5

-, - :

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

Rails ( ActiveSupport, Rails) Array # to_sentence.

Rails ActiveSupport,

['dog', 'cat', 'bird', 'monkey']. to_sentence

result = ", , "

0

Source: https://habr.com/ru/post/1781568/


All Articles