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
?
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.
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.
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.
The $1
is group matched from the regular expression above /(.+)_id$/
. The $1
variable is the string matched in the parenthesis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With