Question

Can some one explain how this enumerable works with example? Data structure wise. What is p in the loop?

(1..10).each_slice(3) {|a| p a}

             [1, 2, 3]
             [4, 5, 6]
             [7, 8, 9]
             [10]
Was it helpful?

Solution

Enumerable#each_slice(n) when called with a block ({ ... }) takes chunks of n elements of the series and passes them to the block as arrays.

The block is an anonymous function with | a | being the argument list. So, a becomes the chunk on each invocation.

p is a built-in function which outputs a presentation of its argument (a) to stdout.

All in all, you are seeing the chunks/slices of three elements (plus the incomplete last one) being printed.

Obviously you've found the Ruby documentation already.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top