Search code examples
rubypseudo-globals

How to use '$MATCH' as an alias of '$&'


According to this document, $MATCH is an alias of $&, and I want to use it for readability.

But it doesn't work in my environment.

'1234-4567'.match(/\d{4}-/){ $& } # => "1234-"
'1234-4567'.match(/\d{4}-/){ $MATCH } # => nil

What am I misunderstanding?


Solution

  • Human names for those [pseudo-]global variables are not enabled by default. You have to require english to use them.

    '1234-4567'.match(/\d{4}-/){ $& } # => "1234-"
    '1234-4567'.match(/\d{4}-/){ $MATCH } # => nil # !> global variable `$MATCH' not initialized
    
    require 'english'
    '1234-4567'.match(/\d{4}-/){ $MATCH } # => "1234-"