2016-06-11 116 views
0

我有健全的代码块一些,而无法理解的语法。我无法做出好的搜索。代码是

keys.map { |k| k =~ /\./; $` } 

什么意思$`?我试着在控制台用它玩,但没有理解它是如何工作

回答

3

当使用正则表达式匹配字符串,则$`当前赛前的字符串相匹配。像这样:

irb> "hello world".match(/world/) 
=> #<MatchData "world"> 
irb> $` 
=> "hello " 

我要补充Ruby的文档以供参考:http://ruby-doc.org/core-2.0.0/doc/globals_rdoc.html

更多信息:

irb> "hello world".match(/world/) 
=> #<MatchData "world"> 
irb> $` 
=> "hello " 
irb> $PREMATCH 
=> nil 
irb> require 'english' 
=> true 
irb> $PREMATCH 
=> "hello " 
irb> 
+0

感谢:如果您使用'english' library,该'可以用一句话预匹配替换您!正是我问 –

+0

为'Regexp'文档列出了[特殊全局变量(http://ruby-doc.org/core-2.3.1/Regexp.html#class-Regexp-label-Special+global+variables )关于正则表达式。 – Stefan

+0

在你的例子,你还可以通过引用它。['MatchData#pre_match'(http://ruby-doc.org/core-2.3.1/MatchData.html#method-i-pre_match) – Stefan