From: Gennady Date: 2003-03-12T09:48:59+09:00 Subject: Re: a newbie question ----- Original Message ----- From: "Daniel Carrera" To: "ruby-talk ML" Sent: Tuesday, March 11, 2003 3:56 PM Subject: Re: a newbie question > Use Array#grep That's what I've been missing in Ruby!!! Thank you very much, Daniel (and Matz, of course). I just verified that Enumerable#grep simply invokes method "===" on its parameter for every element, and that's exactly what I usually need. And with an optional block you get "selective collect" functionality. This is so great!!! Gennady. > > >> %w{ cat dog mouse zebra rhino } > => ["cat", "dog", "mouse", "zebra", "rhino"] > >> %w{ cat dog mouse zebra rhino }.grep(/e/) > => ["mouse", "zebra"] > > On Wed, Mar 12, 2003 at 08:51:13AM +0900, Ben Thomas wrote: > > Hi, > > > > I am trying to create an array from another array using a regular > > expression to compare them. If an element match the regular expression, > > then I want it to appears in my new array, otherwise it can be > > discarded. I have come up with the following code (for example, getting > > strings than end in 'abba' in an array of string) > > > > new_array = (array.collect { |x| if( x =~ /abba$/ ) then x else nil end > > }).compact > > > > It works fine, but I want to know if there's is a more simple way to do > > this since I do this a lot in my scripts. > > > > Thankx, > > Ben. > > > > > > -- > Daniel Carrera > Graduate Teaching Assistant. Math Dept. > University of Maryland. (301) 405-5137 > >