Ruby - String literal single quote vs double quote

Introduction

Here it is again:

Demo

puts 'hello world'

Result

The code above used a string enclosed within single quotes, the second program used a string in double quotes:

Demo

print('Enter your name: ' ) 
name = gets() 
puts( "Hello #{name}" )

Result

Double-quoted strings do more work than single-quoted strings.

They can evaluate themselves as though they were programming code. This is called String interpolation.

To use String interpolation, place string value between a pair of curly brackets preceded by a hash mark (#).

#{name} in a double-quoted string tells Ruby to get the value of the name variable and insert that value into the string itself.

The second line of code calls the gets() method to get some user input, which is then assigned to the variable name.

If the user entered Fred, the final line of code would evaluate the embedded variable, #{name}, and the string "Hello Fred" would be displayed.

Related Topic