Ruby:将变量合并为字符串 [英] Ruby: Merging variables in to a string
问题描述
我正在寻找一种在 Ruby 中将变量合并为字符串的更好方法.
例如,如果字符串类似于:
animal
action
second_animal
"
我有 animal
、action
和 second_animal
的变量,将这些变量放入字符串的首选方法是什么?
惯用的方式是这样写:
#{animal} #{action} #{second_animal}"
注意字符串周围的双引号 ("):这是 Ruby 使用其内置占位符替换的触发器.您不能用单引号 (') 替换它们,否则字符串将保持原样.>
I'm looking for a better way to merge variables into a string, in Ruby.
For example if the string is something like:
"The animal
action
the second_animal
"
And I have variables for animal
, action
and second_animal
, what is the prefered way to put those variables in to the string?
The idiomatic way is to write something like this:
"The #{animal} #{action} the #{second_animal}"
Note the double quotes (") surrounding the string: this is the trigger for Ruby to use its built-in placeholder substitution. You cannot replace them with single quotes (') or the string will be kept as is.
这篇关于Ruby:将变量合并为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!