首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Ruby:将变量合并到字符串中

Ruby:将变量合并到字符串中
EN

Stack Overflow用户
提问于 2009-02-16 21:40:25
回答 5查看 133K关注 0票数 106

我正在寻找一种用Ruby将变量合并成字符串的更好的方法。

例如,如果字符串类似于:

"The animal action the second_animal

我有用于animalactionsecond_animal的变量,将这些变量放入字符串的首选方法是什么?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-02-16 21:42:11

惯用的方法是这样写:

代码语言:javascript
复制
"The #{animal} #{action} the #{second_animal}"

注意字符串两边的双引号("):这是Ruby使用内置占位符替换的触发器。你不能用单引号(')替换它们,否则字符串将保持原样。

票数 265
EN

Stack Overflow用户

发布于 2009-02-16 22:42:04

您可以使用类似sprintf的格式将值注入到字符串中。为此,字符串必须包含占位符。将参数放入数组中,并使用以下方法中的一种:(有关更多信息,请参阅the documentation for Kernel::sprintf。)

代码语言:javascript
复制
fmt = 'The %s %s the %s'
res = fmt % [animal, action, other_animal]  # using %-operator
res = sprintf(fmt, animal, action, other_animal)  # call Kernel.sprintf

您甚至可以显式指定参数编号并对其进行调整:

代码语言:javascript
复制
'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']

或者使用散列键指定参数:

代码语言:javascript
复制
'The %{animal} %{action} the %{second_animal}' %
  { :animal => 'cat', :action=> 'eats', :second_animal => 'mouse'}

请注意,必须为%运算符的所有参数提供一个值。例如,您无法避免定义animal

票数 124
EN

Stack Overflow用户

发布于 2011-09-15 08:09:33

代码语言:javascript
复制
["The", animal, action, "the", second_animal].join(" ")

是另一种方式。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/554666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档