Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Merging variables in to a string

Tags:

string

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?

like image 578
FearMediocrity Avatar asked Feb 16 '09 21:02

FearMediocrity


People also ask

How do you append to a string in Ruby?

You can use the + operator to append a string to another. In this case, a + b + c , creates a new string. Btw, you don't need to use variables to make this work.

How do you concatenate a string and an integer in Ruby?

Idiom #153 Concatenate string with integer. Create the string t as the concatenation of the string s and the integer i. auto t = s + std::to_string (i);

What is interpolation in Ruby?

String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals.


1 Answers

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.

like image 148
Mike Woodhouse Avatar answered Sep 19 '22 11:09

Mike Woodhouse