Project

General

Profile

Actions

Feature #6775

closed

Regexp match() for Enumerables

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

Status:
Rejected
Assignee:
-
Target version:
[ruby-core:46616]

Description

=begin
= 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)
ary.map{|item| self.match(item)}
.select{|x|x!=nil}
end
end

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})).
=end

Updated by naruse (Yui NARUSE) over 11 years ago

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

Did you check Array#grep?

Updated by nobu (Nobuyoshi Nakada) over 11 years ago

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

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

$ ruby -e 'p STDIN.grep(/^\w+$/) {$~}'
ddd
fef x
aaa
^D
[#<MatchData "ddd">, #<MatchData "aaa">]

=end

Actions

Also available in: Atom PDF

Like0
Like0Like0