Re: Delete every other value in an array
by Joel VanderWerf other posts by this author
May 10 2008 9:46AM messages near this date
Re: Delete every other value in an array
|
Re: Delete every other value in an array
Tim Conner wrote:
> What is the best way to delete every other value in a ruby array?
> e.g.
> %w(a b c d e f g h i j k)
>
> becomes => [a c e g i k]
>
> thanks
This solution is less elegant and rubylike than some of the others, but
at least it is fairly portable...
a = %w(a b c d e f g h i j k)
n = (a.size/2.0).ceil
n.times do |i|
a[i] = a[2*i]
end
a.slice!(n..-1)
p a # ==> ["a", "c", "e", "g", "i", "k"]
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407
Thread:
Tim Conner
7stud --
S2
David A. Black
7stud --
Joel VanderWerf
Yermej
Robert Dober
Robert Dober
Ara.T.Howard
James Gray
rgs
Ara.T.Howard
Harry Kakueki
Harry Kakueki
Harry Kakueki
Yermej
Ara.T.Howard
|