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

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

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

animal action second_animal

我有 animalactionsecond_animal的变量,把这些变量放到字符串中的首选方法是什么?

137780 次浏览

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.

You can use sprintf-like formatting to inject values into the string. For that the string must include placeholders. Put your arguments into an array and use on of these ways: (For more info look at the documentation for 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

You can even explicitly specify the argument number and shuffle them around:

'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']

Or specify the argument using hash keys:

'The %{animal} %{action} the %{second_animal}' %
{ :animal => 'cat', :action=> 'eats', :second_animal => 'mouse'}

Note that you must provide a value for all arguments to the % operator. For instance, you cannot avoid defining animal.

["The", animal, action, "the", second_animal].join(" ")

is another way to do it.

The standard ERB templating system may work for your scenario.

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"

I would use the #{} constructor, as stated by the other answers. I also want to point out there is a real subtlety here to watch out for here:

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

While strings can be created with single quotes (as demonstrated by the first_name and last_name variables, the #{} constructor can only be used in strings with double quotes.

This is called string interpolation, and you do it like this:

"The #{animal} #{action} the #{second_animal}"

Important: it will only work when string is inside double quotes (" ").

Example of code that will not work as you expect:

'The #{animal} #{action} the #{second_animal}'

You can use it with your local variables, like this:

@animal = "Dog"


@second_animal = "Bird"

"The #{@animal} #{@action} the #{@second_animal}"

the output would be: "The Dog licks the Bird"