English 中文(简体)
Ruby Regrement Indigence / 字符类 / 全球变数语法碰撞?
原标题:Ruby Regexp Interpolation / Character Class / Global Variable Syntax Clash?
  • 时间:2012-05-23 17:41:38
  •  标签:
  • ruby
  • regex

为什么出现这一错误?

    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> 

这应描述字符串的子集,由单个 $ 组成。AFAIU >Ruby s Regefred 引擎 , d t 需要逃脱字符类中的 ,即使它们通常是元字符。

我从错误信息中猜想,当Ruby在双引号中打到 $ 时,Ruby正试图将 $ 内插进来,但是...为什么?顺序很重要。 $ 字符有多重超载行为,所以我对触发此动作的是什么感到迷茫。

PS, 财政年度:

    /[#$]/
    # => SyntaxError: (irb):1: syntax error, unexpected $undefined
    /[$#]/
    # => /[$#]/
    Regexp.new  [$#] 
    # => /[$#]/
    Regexp.new  [#$] 
    # => /[#$]/
    Regexp.new "[#$]"
    # => SyntaxError: (irb):1: syntax error, unexpected $undefined
最佳回答

问题不是 $ ,而是 ,因为 通常用于在双重引用字符串中的变量扩展。 如 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

但问题是,您也可以直接使用 来扩展全球变量, 这解释了您的问题 :

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

因此,解决方案是避开 $ ,因为这将打破弦内插状态机器,使其努力将构造解释为内插:

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

<强 > EDIT

只是为了非常清楚 : () 问题不是 < code> regexm ,而是您在输入 < code> > " #$ > " 时试图扩展一个名为 < code>$ > 的全球变量 :

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

要修补它,你需要 逃避的东西:

puts "#$]"
=> #$]
问题回答

暂无回答




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...