Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

I have an array that is something like this:

arr = [4, 5, 6, 7, 8, 4, 45, 11] 

I want a fancy method like

sub_arrays = split (arr, 3) 

This should return the following: [[4, 5, 6], [7,8,4], [45,11]]

Note: This question is not a duplicate of "How to chunk an array". The chunk question is asking about processing in batches and this question is about splitting arrays.

like image 397
bragboy Avatar asked Oct 05 '10 13:10

bragboy


2 Answers

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 
like image 155
sepp2k Avatar answered Oct 16 '22 09:10

sepp2k


can also utilize this with a specific purpose:

((1..10).group_by {|i| i%3}).values    #=> [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]] 

in case you just want two partitioned arrays:

(1..6).partition {|v| v.even? }  #=> [[2, 4, 6], [1, 3, 5]] 
like image 44
JstRoRR Avatar answered Oct 16 '22 08:10

JstRoRR