10

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...

1
  • 2
    +1 for trying to read the documentation. Commented May 30, 2012 at 22:30

2 Answers 2

19

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"]
$
Sign up to request clarification or add additional context in comments.

3 Comments

Okay, no comment... I checked Enumerator...
Yes, they're quite similar; note that Enumerator actually includes Enumerable as well; you could think of Enumerator like a generic interface to do enumerating things; if you call [1, 2, 3].each or ['sda', 'sdb', 'sdc', 'sdd'].each_slice(2)—both without a block—you'll get an Enumerator instance, which you can then further do things to.
Like ['sda', 'sdb', 'sdc', 'sdd'].each_slice(2).to_a
0

If you need to work with strict pairs you might want to use Enumerable#each_cons method. Here is the difference between each_slice and each_cons:

a = ['a', 'b', 'c', 'd', 'e']
a.each_slice(2) { |i| p i }
# ["a", "b"]
# ["c", "d"]
# ["e"]
a.each_cons(2) { |i| p i }
# ["a", "b"]
# ["b", "c"]
# ["c", "d"]
# ["d", "e"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.