【发布时间】:2010-10-07 23:13:24
【问题描述】:
我正在寻找一种在 Ruby 中将变量合并为字符串的更好方法。
例如,如果字符串是这样的:
“animalactionsecond_animal”
我有 animal、action 和 second_animal 的变量,将这些变量放入字符串的首选方法是什么?
【问题讨论】:
我正在寻找一种在 Ruby 中将变量合并为字符串的更好方法。
例如,如果字符串是这样的:
“animalactionsecond_animal”
我有 animal、action 和 second_animal 的变量,将这些变量放入字符串的首选方法是什么?
【问题讨论】:
惯用的方式是这样写:
"The #{animal} #{action} the #{second_animal}"
注意字符串周围的双引号 ("):这是 Ruby 使用其内置占位符替换的触发器。您不能用单引号 (') 替换它们,否则字符串将保持原样。
【讨论】:
您可以使用类似 sprintf 的格式将值注入字符串。为此,字符串必须包含占位符。将您的参数放入数组并使用以下方式: (更多信息请查看the documentation for Kernel::sprintf。)
fmt = 'The %s %s the %s'
res = fmt % [animal, action, other_animal] # using %-operator
res = sprintf(fmt, animal, action, other_animal) # call Kernel.sprintf
您甚至可以明确指定参数编号并将它们随机排列:
'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']
或者使用哈希键指定参数:
'The %{animal} %{action} the %{second_animal}' %
{ :animal => 'cat', :action=> 'eats', :second_animal => 'mouse'}
请注意,您必须为% 运算符的所有参数提供一个值。例如,你不能避免定义animal。
【讨论】:
["The", animal, action, "the", second_animal].join(" ")
是另一种方法。
【讨论】:
标准 ERB 模板系统可能适用于您的方案。
def merge_into_string(animal, second_animal, action)
template = 'The <%=animal%> <%=action%> the <%=second_animal%>'
ERB.new(template).result(binding)
end
merge_into_string('tiger', 'deer', 'eats')
=> "The tiger eats the deer"
merge_into_string('bird', 'worm', 'finds')
=> "The bird finds the worm"
【讨论】:
如其他答案所述,我将使用 #{} 构造函数。
我还想指出,这里有一个真正的微妙之处需要注意:
2.0.0p247 :001 > first_name = 'jim'
=> "jim"
2.0.0p247 :002 > second_name = 'bob'
=> "bob"
2.0.0p247 :003 > full_name = '#{first_name} #{second_name}'
=> "\#{first_name} \#{second_name}" # not what we expected, expected "jim bob"
2.0.0p247 :004 > full_name = "#{first_name} #{second_name}"
=> "jim bob" #correct, what we expected
虽然可以使用单引号创建字符串(如 first_name 和 last_name 变量所示,#{} 构造函数只能用于带双引号的字符串。
【讨论】:
这称为字符串插值,你可以这样做:
"The #{animal} #{action} the #{second_animal}"
重要提示:仅当字符串在双引号(“”)内时才有效。
无法按预期工作的代码示例:
'The #{animal} #{action} the #{second_animal}'
【讨论】:
您可以将它与本地变量一起使用,如下所示:
@animal = "Dog"
@action = "licks"
@second_animal = "Bird"
"The #{@animal} #{@action} the #{@second_animal}"
输出将是:“狗 舔 鸟”
【讨论】: