> Hi all,
>
> Here's a ruby question. I've tried my google fu but I can't really
> find the right term for it. Is there an Array or Enumerable method
> to do this?
>
> I want to get elements 0, 2, 4 first. and then display elements 1,3
a.partition {|obj| a.index(obj) % 2 == 0}
=> [["a", "c"], ["b", "d"]]
might not work if obj repeats
> Hi all,
>
> Here's a ruby question. I've tried my google fu but I can't really
> find the right term for it. Is there an Array or Enumerable method
> to do this?
>
> I want to get elements 0, 2, 4 first. and then display elements 1,3
Righteous hack alert!
a = %w( a b c d)
=> ["a", "b", "c", "d"]
h = Hash[*a]
=> {"a"=>"b", "c"=>"d"}
irb(main):012:0> h.keys
=> ["a", "c"]
irb(main):013:0> h.values
=> ["b", "d"]
101 Ways to skin a cat
arr = [ :a, :x, :b, :y, :c, :z ]
odds = []
evens = []
arr.each_with_index { |v,i| (i.odd? ? odds : evens) << v }
Cheers
Phil
Only problem is that a hash's keys and values aren't guaranteed to retain their order..
Tim.
> Only problem is that a hash's keys and values aren't guaranteed to
> retain their order..
Good point. It might until you add something to the hash which you
wouldn't in this case. It's still a hack though. I think Phil's
solution is the best.
Won't work if there are an odd number of elements in the array.
101 Ways to skin a cat
arr = [ :a, :x, :b, :y, :c, :z ]
odds = []
evens = []
arr.each_with_index { |v,i| (i.odd? ? odds : evens) << v }
Cheers
Phil
Why bother with the arr variable?
self.zip((1..self.length).to_a).
select {|v,i| i % 2 == 1}.
collect {|v,i| v}
(I think I've been polluted with programming in Haskell recently; I
keep trying to be point-free.)
-- michael
See now your changing the requirements. The problem used to be odd AND
even. Even only is much simpler. It's lucky we're all so damn agile.
Henry
PS Haskell, pfffffftttttttt