Project

General

Profile

Feature #6775

Updated by naruse (Yui NARUSE) over 12 years ago

Regexp.match() currently works on strings only. 
 I'd like to suggest to extend that to Enumerables, 
 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. 



























Back