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?
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.
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);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With