Finding a regex match from an array of regexes
def match_line regex
@line.match(regex) if !regex.is_a?(Array)
regex.each {|rgx|
results = @line.match(rgx)
return results if !results.nil?
}
return nil
end
This looks like something that could be done in a one line idiomatic way, and I'm just not 开发者_StackOverflow中文版seeing how.
[*regex].map{ |re| @line.match re }.compact.first
or
Array(regex).map{ |re| @line.match re }.compact.first
[*regex].find{|r| @line.match(r)}
return $~ #will return the last MatchedData returned, otherwise nil.
$~
will return the last MatchedData returned, otherwise nil.
def match_line regex
[*regex].each { |r| return r if (r = @line.match r) }
end
It is a preferred, established practice to pass arguments in this case like
match_line(regex1, regex2, ...)
or
match_line(*array_of_regexes)
rather than
match_line([regex1, regex2, ...])
or
match_lines(array_of_regexes)
so your conditioning regarding array-ness is unnecessary.
def match_line *regex
regex.detect{|r| @line =~ r}
Regexp.last_match
end
精彩评论