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...
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"]
$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With