简体   繁体   中英

Joining an array of words / phrases with Ruby

irb(main):001:0> a =  ["global climate change", "calamity", "glaciers", "new york times"]
  => ["global climate change", "calamity", "glaciers", "new york times"]
irb(main):002:0> a.join(', ')
  => "global climate change, calamity, glaciers, new york times"

I need the result to be

  => "global climate change", "calamity", "glaciers", "new york times"

Ideas? A one-liner would be ideal.

The correct way to pass arrays of options to a query via ActiveRecord is just to use query parameters:

a = ["global climate change", "calamity", "glaciers", "new york times"]
Category.where("name IN (?)", a)
# Generated query:
# Category Load (0.4ms)  SELECT `categories`.* FROM `categories` WHERE (name in ('global climate change','calamity','glaciers','new york times'))

You don't have to do anything special to transform it into a valid SQL fragment. You should specifically avoid formatting strings as SQL fragments, as without careful sanitization, you may open up SQL injection vulnerabilities in your application.

Using arrays in a query is very simple:

arr = ["global climate change", "calamity", "glaciers", "new york times"]
Category.where(:name => arr)

There is absolutely no need to generate some weird string ;)

a =  ["global climate change", "calamity", "glaciers", "new york times"]
=> ["global climate change", "calamity", "glaciers", "new york times"]
%Q!"#{a.join('", "')}"!
=> "\"global climate change\", \"calamity\", \"glaciers\", \"new york times\""
a.map{|e| "\"#{e}\""}.join(', ')
=> "\"global climate change\", \"calamity\", \"glaciers\", \"new york times\""
array = ['bob', 'bill']
new_array_string = array.map { |name| "'#{name}'" }.join(',')
=> "'bob', 'bill'"
User.where("name IN (#{new_array_string})")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM