无法在Ruby中插入特定的字符串格式

时间:2014-09-09 03:22:43

标签: ruby string

在使用第三方Web服务时,我需要遍历一个数组并发出请求。不使用术语变量,此代码可以正常工作。

top_5 = get_top_searches[0..4]
counts = []
top_5.each do |term|
 current_count = @client.request(
    'segmentation',
    event:      "Performed search",
    from_date:  (Date.today - 30.days).strftime("%Y-%-m-%-d"),
    to_date:    Date.today.strftime("%Y-%-m-%-d"),
    where:      'properties["keywords"] == "dogs"'
  )
  counts << [term, current_count]
end
counts

但是,我需要"dogs"作为循环中的变量。以下是的字符串列表。 ([“keywords”]必须加双引号)

'properties["keywords"] == "#{term}"'
"properties[\"keywords\"] == #{term}"
"properties['keywords'] == #{term}"
"'properties["keywords"] == #{term}'"
"'properties[\"keywords\"] == #{term}'"

我没有想法。如何格式化这个字符串以便[“keywords”]被双引号,变量被插值,并且很可能,外引号是单引号?

2 个答案:

答案 0 :(得分:0)

你的第一个选项很接近,除了插值在Ruby中的单引号字符串中不起作用。 "properties[\"keywords\"] == \"#{term}\""会让你到达那里,因为双引号是当天的顺序。

答案 1 :(得分:0)

  

以下是不起作用的字符串列表。 ([&#34;关键字&#34;]必须加双引号)

'properties["keywords"] == "#{term}"'
"properties[\"keywords\"] == #{term}"

第二个有效:

['dogs', 'cats', 'monkeys'].each do |term|
  puts "properties[\"keywords\"] == #{term}"
end

--output:--
properties["keywords"] == dogs
properties["keywords"] == cats
properties["keywords"] == monkeys

好吧,我想你需要在#{term}附近添加双引号:

['dogs', 'cats', 'monkeys'].each do |term|
  puts "properties[\"keywords\"] == \"#{term}\""
end

--output:--
properties["keywords"] == "dogs"
properties["keywords"] == "cats"
properties["keywords"] == "monkeys"

但你很少(如果有的话)必须逃避红宝石中的引号:

%Q{properties["keywords"] == "#{term}"}

%Q{}的作用类似于双引号,您可以使用任何分隔符,例如%Q[], %Q||, %Q**,等。

  

外部引号是单引号?

单引号和双引号都是String构造函数。 Ruby可以关心你使用哪一个 - 它们都创建了字符串。没有带单引号的String这样的东西。如果您要创建的字符串实际上必须包含string[0] == "'"string[-1] == "'",那么您可以执行此操作:

['dogs', 'cats', 'monkeys'].each do |term|
  puts %Q{'properties["keywords"] == "#{term}"'}
end

--output:--
'properties["keywords"] == "dogs"'
'properties["keywords"] == "cats"'
'properties["keywords"] == "monkeys"'

但是,这与以下内容不同:

where: 'properties["keywords"] == "dogs"'

该字符串中的第一个字符是p,该字符串中的最后一个字符是"