30

I'm watching a RailsCast on polymorphic associations. http://railscasts.com/episodes/154-polymorphic-association?view=asciicast

There's three different models Article, Photo and Event that each take a comment from Comment.rb. (Article, Photo and Event each of a article_id, photo_id, and event_id). In listing the comments he has the problem of figuring out which of the 3 models to list the comments for, so he does this in the index action

def index
  @commentable = find_commentable
  @comments = @commentable.comments
end


def find_commentable
  params.each do |name, value|
    if name =~ /(.+)_id$/
      return $1.classify.constantize.find(value)
    end
  end
  nil
end

My question is, what is $1?

Shiva
  • 11,485
  • 2
  • 67
  • 84
Leahcim
  • 40,649
  • 59
  • 195
  • 334

2 Answers2

32

According to Avdi Grimm from RubyTapas

$1 is a global variable which can be used in later code:

 if "foobar" =~ /foo(.*)/ then 
    puts "The matching word was #{$1}"
 end

Output:

"The matching word was bar"

In short, $1, $2, $... are the global-variables used by some of the ruby library functions specially concerning REGEX to let programmers use the findings in later codes.

See this for such more variables available in Ruby.

Shiva
  • 11,485
  • 2
  • 67
  • 84
simchona
  • 1,878
  • 3
  • 19
  • 18
  • its only created when using equal tilde operator?? – Arnold Roa Mar 15 '15 at 16:29
  • 1
    Yes, `$1`, `$2` etc. match the first, second, etc. parenthesized groups in the last regular expression - see link in the answer. Rubocop recommends using `Regexp.last_match(n)` instead (note n is zero based, so `$1` == `#last_match(0)` – MatzFan Jan 19 '18 at 20:26
15

The $1 is group matched from the regular expression above /(.+)_id$/. The $1 variable is the string matched in the parenthesis.

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
chubbsondubs
  • 37,646
  • 24
  • 106
  • 138