Daniel Harple wrote: > > On Mar 12, 2006, at 9:34 PM, Tomas Fischer wrote: > >> Hi, >> >> I've got an array a= [1,2,3,4,5,6] and want to access each second >> element: >> b=[2,4,6]. How is this done in ruby? >> >> I know, that I can use a for-loob and modulo operator, but I think there >> is a "ruby way" of doing this. >> >> Thanks. >> tomas >> >> -- >> Posted via http://www.ruby-forum.com/. >> > > require 'enumerator' > a = (1..10).to_a > p a.enum_for(:each_slice, 2).collect { |m| m[1] } # -> [2, 4, 6, 8, 10] > > -- Daniel > > enumerator is handy but it seems a bit like overkill for a task that can be done with the builtin classes: irb(main):009:0> ary = [1,2,3,4,5,6] => [1, 2, 3, 4, 5, 6] irb(main):010:0> ary2 = [] => [] irb(main):011:0> ary.each_with_index { |a, i| ary2 << a if i % 2 == 1 } => [1, 2, 3, 4, 5, 6] irb(main):012:0> ary2 => [2, 4, 6]