Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError for strings "#$" and "#@"

Tags:

ruby

Can someone explain this behavior to me?

>> "#$"
SyntaxError: (irb):3: unterminated string meets end of file
    from /Users/milan/.rvm/rubies/ruby-1.9.2-head/bin/irb:16:in `<main>'

>> "#@"
SyntaxError: (irb):4: syntax error, unexpected $undefined
(irb):4: unterminated string meets end of file
    from /Users/milan/.rvm/rubies/ruby-1.9.2-head/bin/irb:16:in `<main>'

>> "#$$"
"10994"

Did I miss some new feature of 1.9.2? Confused.

like image 270
Milan Novota Avatar asked Dec 22 '22 09:12

Milan Novota


1 Answers

As you probably know you can use #{ expression } inside a double quoted value to insert the value of expression into the string at that position. A little known sub-feature is that if the expression is just a global or instance variable, you can leave out the braces. I.e. #$foo inside a double quoted string will insert the value of the global variable $foo and #@foo will do the same for instance variables.

So your first two examples error out, because it thinks you want to get the variables $" or @" respectively (the latter of which is not a variable name - though the first one is - which is why you get two error messages for the second and just one for the first), leaving the string unclosed. And the third example simply gives you the value of the variable $$.

If you don't want this to happen you can escape the # with a backslash in front of it (or simply use single quotes instead of double quotes if you don't need any double-quote-specific behavior).

This behavior is not specific to ruby 1.9 - it has always been like this.

like image 111
sepp2k Avatar answered Jan 12 '23 17:01

sepp2k