Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does string interpolation work in Ruby when there are no curly braces?

The proper way to use string interpolation in Ruby is as follows:

name = "Ned Stark" puts "Hello there, #{name}" #=> "Hello there, Ned Stark" 

That is the way I intend to always use it.

However, I've noticed something odd in Ruby's string interpolation. I've noticed that string interpolation works in Ruby without the curly braces in regards to instance variables. For example:

@name = "Ned Stark" puts "Hello there, #@name" #=> "Hello there, Ned Stark" 

And that trying the same thing as a non-instance variable does not work.

name = "Ned Stark" puts "Hello, there, #name" #=> "Hello there, #name" 

I've tried this with success in both 1.9.2 and 1.8.7.

Why does this work? What is the interpreter doing here?

like image 807
Charles Caldwell Avatar asked Apr 10 '12 14:04

Charles Caldwell


People also ask

What is the purpose of string interpolation?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

Is string an interpolation?

String interpolation is a technique that enables you to insert expression values into literal strings. It is also known as variable substitution, variable interpolation, or variable expansion. It is a process of evaluating string literals containing one or more placeholders that get replaced by corresponding values.


1 Answers

According to The Ruby Programming Language by Flanagan and Matsumoto:

When the expression to be interpolated into the string literal is simply a reference to a global, instance or class variable, then the curly braces may be omitted.

So the following should all work:

@var = "Hi" puts "#@var there!"  #=> "Hi there!"  @@var = "Hi" puts "#@@var there!" #=> "Hi there!"  $var = "Hi" puts "#$var there!"  #=> "Hi there!" 
like image 70
tsherif Avatar answered Oct 11 '22 07:10

tsherif