Need to split arrays to sub arrays of specified size in Ruby [duplicate]

arr.each_slice(3).to_a

each_slice returns an Enumerable, so if that’s enough for you, you don’t need to call to_a.

In 1.8.6 you need to do:

require 'enumerator'
arr.enum_for(:each_slice, 3).to_a

If you just need to iterate, you can simply do:

arr.each_slice(3) do |x,y,z|
  puts(x+y+z)
end

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)