Ruby # {} is not variable expansion

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

Ruby # {} is not variable expansion
ruby constant variable
Yarn is not installed
What is @ (instance variable)?
Variable type in ruby
[Ruby] What is true?
DateFormat is not thread safe
"tx" is not bound error
Ruby classes are constants, not
Is Ruby all objects, true?
Ruby version does not switch
[Ruby] What is `!!` used for?
[Ruby] What is an instance?
[Rails] fields_for is not displayed
I tried to make Numeron which is not good in Ruby
Uncaught ReferenceError: Vue is not defined
Ruby on Rails variable, constant summary
Ruby's attr_accessor is not an accessor
Divide by Ruby! Why is it 0?
that? WebView (swift) is not working.
[Ruby on Rails] What is Bcrypt?
rails AWS deployment is not reflected
What is a reference type variable?
Java Calendar is not a singleton.
Is there no type in Ruby?
Data is not registered in Rails.
This problem is soberly difficult ... (Ruby)
Why Java Vector is not used
What is a Ruby 2D array?
"" Application.js "is not present in the asset pipeline" error in Ruby on Rails
[Error] Regarding rbenv: ruby 2.5.1 is not installed ot ~ when executing automatic deployment
If rbenv install is not successful, try using the environment variable "RUBY_BUILD_CURL_OPTS".