Mike Belyakov Mike Belyakov - 5 months ago 22
Ruby Question

Ruby 2 syntax, $ `

I've sound some chunk of code, and can not understand the syntax. And I can not make good search. The code is

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


What mean $` ? I tried to play with it in console, but did not understood how it works

Answer

When using regex to match a string, the $` matches the string before the current match. Like so:

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

I should add the Ruby doc for reference: http://ruby-doc.org/core-2.0.0/doc/globals_rdoc.html

More info: If you use the 'english' library, the ` can be replaced with the word PREMATCH:

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