String substitution in ruby depends on variable's first character

101 Views Asked by At

After I thought the variable scope would be the reason I got the hint, that substitution depends on if the first character of a variable is a letter/underscore or not. But I don't understand the intention. Let's take this example:

$var1 = "bar"
_var2 = "bar"
var3 = "bar"
Var4 = "bar"
@var5 = "bar"
puts "foo #$var1"
puts "foo #_var2"
puts "foo #var3"
puts "foo #Var4"
puts "foo #@var5"

which results in this:

foo bar
foo #_var2
foo #var3
foo #Var4
foo bar

I would expect for all 5 lines the same. Is it a bug? Or what's the intention of this behaviour?

1

There are 1 best solutions below

2
On

It is not about scope. The issue here is whether {} after # can be omitted in interpolation. If you put {}, then any of them above will work. When you have a variable starting with a non-letter character (a character other than alphabet or underscore, i.e., $ or @), you can omit the {}. If you omit {} when you cannot, then it will not be interpolated.