简体   繁体   English

用Ruby连接单词/词组

[英]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: 通过ActiveRecord将选项数组传递给查询的正确方法是使用查询参数:

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. 您无需执行任何特殊操作即可将其转换为有效的SQL片段。 You should specifically avoid formatting strings as SQL fragments, as without careful sanitization, you may open up SQL injection vulnerabilities in your application. 您应该特别避免将字符串格式化为SQL片段,因为如果不仔细进行清理,可能会在应用程序中打开SQL注入漏洞。

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})")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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