tags:

views:

72

answers:

1

Hi,

Let's say I've array with n elements. I want to take first ten elements and do something with them and then next ten and so on until array is done.

What's the right Ruby way to do it? (With c-language background I could write some for-loop and inside the loop count to ten, do stuff and set my bookkeeping variable to zero and continue main array handling..)

+9  A: 
#!/usr/bin/ruby1.8

a = (1..10).to_a
a.each_slice(3) do |slice|
  p slice    # => [1, 2, 3]
             # => [4, 5, 6]
             # => [7, 8, 9]
             # => [10]
end
Wayne Conrad
Wayne, perfect thanks!
MJo
As far as I know, `Enumerable#each_slice` has been defined in enumerator (which was stdlib before 1.8.7 and has been merged into core in 1.9/1.8.7) for as long as enumator existed. It certainly has been in 1.8.6. In other words: if you put `require 'enumerator'` at the beginning, this will work on 1.8.6 just fine.
sepp2k
@sepp2k, Thanks. I misread the latest Pickaxe: Apprently "1.9" in the sidebar means, in this case, "behavior change in 1.9," and not "completely new for 1.9". In other places in the same book, "1.9" in the sidebar means "didn't even exist before 1.9." Joy.
Wayne Conrad