From: William James Date: 2007-08-25T05:20:04+09:00 Subject: Re: Selecting indices from an array On Aug 24, 1:44 pm, m...@tidbits.com (matt neuburg) wrote: > William James wrote: > > On Aug 23, 8:08 am, "Ronald Fischer" > > wrote: > > > > If this is a > > > > problem, you can use this: > > > > > a.enum_for(:each_with_index).inject([]){|res, i| > > > > i[0].match( /g$/) ? res << i[1] : res > > > > } > > > > This is an idea I like! Thanks a lot! > > > > Ronald > > > -- > > > Ronald Fischer > > > Phone: +49-89-452133-162 > > > accum = [] > > a.each_with_index{|s,i| accum << i if s =~ /g$/ } > > And to generalize further, let's abstract the test (it shouldn't matter > what the test is, just as it shouldn't matter what the array is): > > #specific part > a=%w(Deutschlandsberg Stainz Preding Eibiswald) > test = Proc.new {|s| s=~/g$/} Why so prolix? test = proc{|s| s =~ /g$/} > > #general part > result = [] > a.each_with_index {|ss,ix| result << ix if test.call(ss)} > > Or, even more general (because the names stop mattering): > > def indices_matching_test(a) > result = [] > a.each_with_index {|ss,ix| result << ix if yield ss} > result > end > > #and here's how to use it: > a=%w(Deutschlandsberg Stainz Preding Eibiswald) > test = Proc.new {|s| s=~/g$/} > puts indices_matching_test(a, &test) Even better: p indices_matching_test(a){|s| s =~ /g$/}