我正在寻找一种用Ruby将变量合并成字符串的更好的方法。
例如,如果字符串类似于:
"The animal
action
the second_animal
“
我有用于animal
、action
和second_animal
的变量,将这些变量放入字符串的首选方法是什么?
发布于 2009-02-16 21:42:11
惯用的方法是这样写:
"The #{animal} #{action} the #{second_animal}"
注意字符串两边的双引号("):这是Ruby使用内置占位符替换的触发器。你不能用单引号(')替换它们,否则字符串将保持原样。
发布于 2009-02-16 22:42:04
您可以使用类似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
。
发布于 2011-09-15 08:09:33
["The", animal, action, "the", second_animal].join(" ")
是另一种方式。
https://stackoverflow.com/questions/554666
复制相似问题