1
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 seeing how.

2
  • 1
    Your question isn't clear. Do you want to see if one of the regex patterns in the array matches something? Or, do you want to find out which of the regex patterns matched? Commented Apr 16, 2011 at 19:23
  • You meant to put return before the second line, I suppose. Commented Apr 16, 2011 at 19:46

4 Answers 4

5
[*regex].map{ |re| @line.match re }.compact.first

or

Array(regex).map{ |re| @line.match re }.compact.first
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, that is great. Does the Array() turn a variable into an array if it isn't already one? Also, I assume all of the regexes are matched and there isn't a way to jump out after the first match?
nm on Array().. that's a very useful function.
That's correct, it will iterate over all regexes in regex, but assuming there are relatively few this won't be a big deal. You could do a custom each that short-circuits but I doubt the performance gain would be worth the loss in readability.
1
 [*regex].find{|r| @line.match(r)}
 return $~ #will return the last MatchedData returned, otherwise nil.

$~ will return the last MatchedData returned, otherwise nil.

2 Comments

:( perlish magic global variables are unreadable, as indicated by your explaining comment.
Having a comment associated with that line seems like no issue to me, especially because it is literally one line that is in question.
0
def match_line regex
  [*regex].each { |r| return r if (r = @line.match r) }
end

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.