Project

General

Profile

Feature #6775

Updated by nobu (Nobuyoshi Nakada) over 11 years ago

=begin 
 = Abstract 

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

 I am aware of the (({grep})) grep method in (({Enumerable})). Enumerable. 
 But the (({grep})) grep method does return the matching elements, 
 while I'm looking for an method to return the ((*match result*)) *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})) Regexp or (({Enumerable})). 
 =end 
 Enumerable.

Back