8/18


#1

Why do we print "#{i}", not only i? Seems they both have the same result on the console? SO what is the difference?


#2

If the member still has some interest in the question, please reply back.

"#{expression}" is known as variable interpolation and permits us to insert any expression into a string. puts will treat everything as string data so there is no type dependency.

There is scope, like always on the variables.

Ruby Strings

Now let's go one step further and consider the variable i being concatenated into a string.

puts "string data with a number: " + i + ", where we inserted it"

Ruby will not like this and will tell us we cannot concatenate numbers in strings. Variable interpolation handles this, nicely. As your reading will have shown, we can also use string formatting:

name = 'Logan'
age = 10
puts "My grandson is %s, and he is %d." % [name, age]
# My grandson is Logan, and he is 10

But, unlike interpolation, these inserts are of specified type.