Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: What does $1 mean?

Tags:

ruby

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?

like image 838
Leahcim Avatar asked Feb 25 '12 04:02

Leahcim


People also ask

What are variables Ruby?

Ruby variables are locations which hold data to be used in the programs. Each variable has a different name. These variable names are based on some naming conventions. Unlike other programming languages, there is no need to declare a variable in Ruby.

How to match string in Ruby?

Ruby | Regexp match() functionRegexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search. Return: regular expression with the string after matching it.


2 Answers

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.

like image 77
simchona Avatar answered Nov 15 '22 13:11

simchona


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

like image 15
chubbsondubs Avatar answered Nov 15 '22 11:11

chubbsondubs