Feature #6775

Regexp match() for Enumerables

Added by eike.rb (Eike Dierks) over 8 years ago. Updated over 8 years ago.

Target version:


= Abstract

(({Regexp.match()})) currently works on strings only.
I'd like to suggest to extend that to (({Enumerable}))s,
possibly giving it a different name like (({match_array()}))

I am aware of the (({grep})) method in (({Enumerable})).
But the (({grep})) method does return the matching elements,
while I'm looking for an method to return the ((match result)) as applied to the elements.

= Description

I'm actually looking for a canonical way to solve a frequent problem in file parsing.

Let's assume I have a file read into an array of lines.
I now want to select specific lines from that file
and at the very same time extract fields from these lines.

Obviously applying a regexp can do both of these tasks at the very same time.
But I did not yet find a primitive in the ruby1.9 to do this in one strike.

I came up with this snippet:
class Regexp
# match all items in array an return only the matching ones
def match_array(ary){|item| self.match(item)}

One of the remarkable things is,
that selecting non nil items is included,
which makes some sense when matching items form an enumerable.

By not having nil items in the result of that operation,
aka by only having matching items in the result,
we can easily work with the results,
aka accessing the matches.

I'm not really sure if this should go into (({Regexp})) or (({Enumerable})).

Updated by naruse (Yui NARUSE) over 8 years ago

  • Description updated (diff)
  • Status changed from Open to Feedback

Did you check Array#grep?

Updated by nobu (Nobuyoshi Nakada) over 8 years ago

  • Description updated (diff)
  • Status changed from Feedback to Rejected

Note that (({Enumerable#grep})) can take a block.

$ ruby -e 'p STDIN.grep(/\w+$/) {$~}'
fef x
[#, #]


Also available in: Atom PDF