문제

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]
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top