Jeremy Smith
Jeremy Smith

Reputation: 15079

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

Upvotes: 1

Views: 2747

Answers (4)

sawa
sawa

Reputation: 168269

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

Upvotes: 0

DigitalRoss
DigitalRoss

Reputation: 146261

def match_line regex
  [*regex].each { |r| return r if (r = @line.match r) }
end

Upvotes: 0

Rein Henrichs
Rein Henrichs

Reputation: 15605

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

or

Array(regex).map{ |re| @line.match re }.compact.first

Upvotes: 5

Mike Lewis
Mike Lewis

Reputation: 64177

 [*regex].find{|r| @line.match(r)}
 return $~ #will return the last MatchedData returned, otherwise nil.

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

Upvotes: 1

Related Questions