ironsand
ironsand

Reputation: 15151

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?

Upvotes: 1

Views: 54

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

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-"

Upvotes: 4

Related Questions