Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby array loop always pair

Tags:

arrays

loops

ruby

I've got the following array:

a = ['sda', 'sdb', 'sdc', 'sdd']

Now I want to loop through these entries but always with two elements. I do this like the following at the moment:

while b = a.shift(2)
  # b is now ['sda', 'sdb'] or ['sdc', 'sdd']
end

This feels somehow wrong, is there a better way to do this? Is there a way to get easily to something like [['sda', 'sdb'], ['sdc', 'sdd']] ?

I read http://www.ruby-doc.org/core-1.9.3/Array.html but I didn't find something useful...

like image 485
Raffael Schmid Avatar asked May 30 '12 12:05

Raffael Schmid


1 Answers

You might want to look at Enumerable instead, which is included in Array.

The method you want is Enumerable#each_slice, which repeatedly yields from the enumerable the number of elements given (or less if there aren't that many at the end):

a = ['sda', 'sdb', 'sdc', 'sdd']
a.each_slice(2) do |b|
    p b
end

Yields:

$ ruby slices.rb 
["sda", "sdb"]
["sdc", "sdd"]
$
like image 119
Asherah Avatar answered Sep 28 '22 22:09

Asherah