Ruby:将variables合并到一个string中
我正在寻找一种更好的方法来在Ruby中将variables合并到一个string中。
例如,如果string是这样的:
 “ animal action第二animal ” 
 而且我有animal , action和second_animalvariables,将这些variables放入string的首选方法是什么? 
惯用的方法是写这样的东西:
 "The #{animal} #{action} the #{second_animal}" 
注意包围string的双引号(“):这是Ruby使用其内置占位符replace的触发器,不能用单引号(')replace它们,否则string将保持原样。
您可以使用类似sprintf的格式将值注入到string中。 为此,string必须包含占位符。 把你的参数放到一个数组中,并用这些方法:(更多信息请看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 。 
 正如其他答案所述,我将使用#{}构造函数。 我也想指出这里有一个真正的微妙之处,要注意这里: 
 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 
 虽然可以用单引号创buildstring(如first_name和last_namevariables所示, 但只能在带有双引号的string中使用#{}构造函数。 
 ["The", animal, action, "the", second_animal].join(" ") 
是另一种方式来做到这一点。
这被称为string插值,你这样做:
 "The #{animal} #{action} the #{second_animal}" 
重要说明:只有当string在双引号(“”)内时才会起作用。
代码的示例不会按预期工作:
 'The #{animal} #{action} the #{second_animal}' 
标准的ERB模板系统可能适用于您的scheme。
 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" 
你可以使用你的局部variables,如下所示:
 @animal = "Dog" 
 @action = "licks" 
 @second_animal = "Bird" 
 "The #{@animal} #{@action} the #{@second_animal}" 
输出结果是:“ 狗 舔 鸟 ”