Look at the code below.
name = "Ruby"
puts "Hello, #{ name }!"
When executed
Hello, Ruby!
Is displayed.
There is a part called # {name}
in the string literal on the second line.
There are a lot of articles that describe this as "variable expansion", but unlike those of PHP and Perl, in the case of Ruby, it is essentially that you can write expressions inside **. It's important [^ pp].
Therefore, it is called Expression Expansion.
[^ pp]: I don't know what's going on with the latest version of PHP. Also in PHP, there is a way to write an expression in the variable expansion. Reference: Expand expression to string literal in PHP --Qiita
You can do the following:
scores = {
Foo: 3,
Bar: 8,
Baz: 5,
}
puts "Total score of #{ scores.keys.join(", ") } is #{ scores.values.sum }."
# => Total score of Foo, Bar, Baz is 16.
Please do not use the tsukkomi saying that it is strange as English [^ fbb]. Also, whether it is better to enter a complicated expression like this is another matter.
[^ fbb]: You should write "Foo, Bar, and Baz" or "Foo, Bar and Baz". I don't know.
In this example, " "
is used in the expression expansion of the string literal described by " "
, but it can be seen that it is interpreted as intended without any problem.
Even so, the term "expression ** expansion **" is a little tricky. What is deployment? I wonder if "expression embedding" or "expression insertion" was not good.
Recommended Posts