Adam Shelly
3/13/2006 12:01:00 AM
On 3/12/06, Luc Heinrich <luc@honk-honk.com> wrote:
> On 12 mars 06, at 21:34, Tomas Fischer wrote:
>
> > 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?
>
> irb(main):001:0> a = [1,2,3,4,5,6]
> => [1, 2, 3, 4, 5, 6]
> irb(main):002:0> a.select {|e| a.index(e) % 2 == 1 }
> => [2, 4, 6]
>
> --
That's a problem if there are duplicates in the array:
irb(main):012:0> a=[1,1,2,2,3,3,4,5]
=> [1, 1, 2, 2, 3, 3, 4, 5]
irb(main):013:0> a.select{|e| a.index(e) %2 == 1}
=> [5]
irb(main):014:0> s=true
=> true
irb(main):015:0> a.select{s=!s}
=> [1, 2, 3, 5]
irb(main):016:0>
-Adam