Ruby:将变量合并为字符串 [英] Ruby: Merging variables in to a string

查看:41
本文介绍了Ruby:将变量合并为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 Ruby 中将变量合并为字符串的更好方法.

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

animal action second_animal"

我有 animalactionsecond_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆