我正在寻找一种更好的方法将变量合并到一个字符串中,在Ruby中.
例如,如果字符串是这样的:
"的animal action的second_animal"
我有变量animal,action并且second_animal,将这些变量放入字符串的首选方法是什么?
Mik*_*use 232
惯用的方法是写这样的东西:
"The #{animal} #{action} the #{second_animal}"
Run Code Online (Sandbox Code Playgroud)
请注意字符串周围的双引号("):这是Ruby使用其内置占位符替换的触发器.您不能用单引号(')替换它们,否则字符串将保持原样.
gix*_*gix 108
您可以使用类似sprintf的格式将值注入字符串.为此,字符串必须包含占位符.将您的参数放入数组并使用以下方法:(有关更多信息,请查看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
Run Code Online (Sandbox Code Playgroud)
您甚至可以显式指定参数编号并将其随机播放:
'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']
Run Code Online (Sandbox Code Playgroud)
或者使用哈希键指定参数:
'The %{animal} %{action} the %{second_animal}' %
{ :animal => 'cat', :action=> 'eats', :second_animal => 'mouse'}
Run Code Online (Sandbox Code Playgroud)
请注意,您必须为%运算符的所有参数提供值.例如,你无法避免定义animal.
Sta*_*ers 16
我将使用#{}构造函数,如其他答案所述.我还想指出这里有一个非常微妙的细节需要注意:
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
Run Code Online (Sandbox Code Playgroud)
虽然可以使用单引号创建字符串(如first_name和last_name变量所示,但#{}构造函数只能在带双引号的字符串中使用).
And*_*imm 13
["The", animal, action, "the", second_animal].join(" ")
Run Code Online (Sandbox Code Playgroud)
是另一种方法.
这称为字符串插值,你这样做:
"The #{animal} #{action} the #{second_animal}"
Run Code Online (Sandbox Code Playgroud)
重要提示:只有当字符串在双引号("")内时才会起作用.
无法按预期工作的代码示例:
'The #{animal} #{action} the #{second_animal}'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113048 次 |
| 最近记录: |