2

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?

Cody Gray
  • 230,875
  • 49
  • 477
  • 553

1 Answers1

3

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.

sawa
  • 160,959
  • 41
  • 265
  • 366
  • `When you have a variable starting with a non-letter character (alphabet or underscore), you can omit the {}` - this is not true having given examples. :) – BroiSatse May 09 '14 at 22:23
  • @BroiSatse Oops, it was the opposite. I fixed. – sawa May 09 '14 at 22:28