[英]Ruby: What does $1 mean?
我正在觀看關於多態關聯的RailsCast。 http://railscasts.com/episodes/154-polymorphic-association?view=asciicast
有三種不同的模型文章,照片和事件,每個都評論來自Comment.rb。 (article_id,photo_id和event_id各自的文章,照片和事件)。 在列出評論時,他有問題找出列出評論的3個模型中的哪一個,所以他在索引動作中這樣做
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
我的問題是,什么是$1
?
$ 1是一個全局變量,可以在以后的代碼中使用:
if "foobar" =~ /foo(.*)/ then puts "The matching word was #{$1}" end
輸出 :
“匹配的單詞是吧”
簡而言之,$ 1,$ 2,$ ...是一些全局變量,由一些特別涉及REGEX
的ruby庫函數使用,讓程序員在后面的代碼中使用這些結果。
有關 Ruby中可用的更多變量,請參見此處。
$1
是從上面的正則表達式/(.+)_id$/
匹配的組。 $1
變量是括號中匹配的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.