Last Updated: February 25, 2016
·
1.124K
· peterpengnz

ruby iterating an array with n elements at a time

peter:~ > ruby -r enumerator -e'  %w( 1 2 3 4 5 ).each_slice(2){|slice| p slice}  '

["1", "2"]
["3", "4"]
["5"]


peter:~ > ruby -r enumerator -e'  %w( 1 2 3 4 5 ).each_cons(2){|slice| p slice}  '

["1", "2"]
["2", "3"]
["3", "4"]
["4", "5"]

Here is the result of using each_slice method to get three columns view of a list of potential harms in work place.

Picture