ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> ruby-talk
ruby-talk
Re: Delete every other value in an array
by David A. Black other posts by this author
May 10 2008 11:10AM messages near this date
Re: Delete every other value in an array | Re: Delete every other value in an array
Hi --

On Sun, 11 May 2008, 7stud -- wrote:

>  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
> 
> 
>  letters = ("a".."z").to_a
>  last_index = letters.length - 1
> 
>  results = []
> 
>  0.step(last_index, 2) do |i|
>   results << letters[i]
>  end
> 
>  letters = results
>  p letters

In Ruby 1.9 you can do:

   letters.values_at(*0.step(letters.size-1,2))

using the enumerator returned from step called without a block.


David

-- 
Rails training from David A. Black and Ruby Power and Light:
   INTRO TO RAILS         June 9-12            Berlin
   ADVANCING WITH RAILS   June 16-19           Berlin
   INTRO TO RAILS         June 24-27           London (Skills Matter)
See http://www.rubypal.com for details and updates!
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

Privacy Policy | Email Opt-out | Feedback | Syndication
© 2004 ActiveState, a division of Sophos All rights reserved