From: Mark Van Holstyn Date: 2006-04-13T10:04:21+09:00 Subject: Re: map_if, collect_if ??? ------=_Part_12126_19317626.1144890257913 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline Try using the 'select' method... irb(main):002:0* a =3D [ 1,2,3,4,5 ] irb(main):003:0> b =3D a.select { |i| irb(main):004:1* (i % 2 !=3D 0) and (i * 10) irb(main):005:1> } =3D> [1, 3, 5] On 4/12/06, Bruce Woodward wrote: > > Hi, > > I have been through the pickaxe book, looking at the array and enumerable > built-in class and module and can't find a way of achieving a map_if or > collect_if. > From pickaxe, collect "Returns a new array containing the results of > running > block once for every element in enum". Of course map is an alias to > collect. > There is find_all but it returns an array containing the elements of enum= , > not the results of running the block, so I have written one. > Is there a better way that already exists? > thanks, > Bruce. > > module Enumerable > > # returns an array containing the results of running block once for > every > element in enum, for which block > # is not false. > def map_if > rt, r =3D [], nil > self.each { |e| (r =3D yield(e)) and rt << r } > rt > end > alias :collect_if :map_if > > end > > a =3D [ 1,2,3,4,5 ] > > b =3D a.map_if { |i| > (i % 2 !=3D 0) and (i * 10) > } > > p b ## [10, 30, 50] > > -- Mark Van Holstyn mvette13@gmail.com http://lotswholetime.com ------=_Part_12126_19317626.1144890257913--