SyntaxError...">

Ruby Regexp Interpolation / Character Class / Global Variable Syntax Clash?

Why is this error occurring?

    Regexp.new("[#$]")
    # => SyntaxError: (irb):1: syntax error, unexpected $undefined
    # => Regexp.new("[#$]")
    #              ^
    # (irb):1: unterminated string meets end of file
    #     from ~/.rvm/rubies/ruby-1.9.3-p194/bin/irb:1:in `<main>'

This should describe a subset of strings consisting of one character $or #, literally. And, AFAIU Ruby Regexp engine , #and you $ do not need to avoid inside the character class, even if they are usually metacharacters.

I would suggest from the error message that Ruby is trying to interpolate $when hit by #double quotes, but ... why? Ordering is important. Symbols $and #have several overloaded actions, so I don’t understand what kind of launch it is.

PS, FYI:

    /[#$]/
    # => SyntaxError: (irb):1: syntax error, unexpected $undefined
    /[$#]/
    # => /[$#]/
    Regexp.new '[$#]'
    # => /[$#]/
    Regexp.new '[#$]'
    # => /[#$]/
    Regexp.new "[#$]"
    # => SyntaxError: (irb):1: syntax error, unexpected $undefined
+5
source share
1 answer

$, #, #... . "#{x}".

#$global, :

$global = "hello"
"#$global"
=> "hello"

, , #, $, , - , :

puts "\#$global"
=> #$global
puts "#\$global"
=> #$global

, . Regexp, $] "#$]":

puts "#$]"
SyntaxError: (irb):22: syntax error, unexpected $undefined

, - :

puts "\#$]"
=> #$]
+7

All Articles