While reading Yehuda Katz’ blog post concerning mental models about Ruby’s behavior, I was a bit rankled by his reference to implicit locals created by running regular expressions with match clauses.

I was nearly certain that the dollar-sign prefix on the variables ensured the variables were global, but had to verify for myself.

Surprisingly, I found that the matches truly were local.

class RegGlobalTester
  def hello
    [ $1, "hello".match(/h/), goodbye, $1 ]
  def goodbye
    [ $1, "goodbye".match(/(g)/), $1 ]

 => [nil, #<MatchData "h">, [nil, #<MatchData "g" 1:"g">, "g"], nil]

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.