For this one we’ll operate on an Array.
The procedure looks like this:
src = [1, 2, 3, 4, 5]
dest = []
chunksize = 2
i = 0
until dest.size >= (src.size.to_f / chunksize).ceil
dest << src[i, chunksize]
i += chunksize
end
As an Array function ‘chunk’:
class Array
def chunk(chunksize)
raise ArgumentError, "chunk size must be > 0" if chunksize < 1
dest = []
i = 0
until dest.size >= (size.to_f / chunksize).ceil
dest << self[i, chunksize]
i += chunksize
end
dest
end
end
This feels long and not very ruby-ish, but I’m still pretty new to Ruby. Feel free to edit as you see fit.
If you’re using Rails (this won’t work in plain ruby until 1.9) you can use _in_groups_of_
src = [1, 2, 3, 4, 5]
dest = []
src.in_groups_of(2) {|n| dest << n}
For this one we’ll operate on an Array.
The procedure looks like this:
src = [1, 2, 3, 4, 5]
dest = []
chunksize = 2
i = 0
until dest.size >= (src.size.to_f / chunksize).ceil
dest << src[i, chunksize]
i += chunksize
end
As an Array function ‘chunk’:
class Array
def chunk(chunksize)
raise ArgumentError, "chunk size must be > 0" if chunksize < 1
dest = []
i = 0
until dest.size >= (size.to_f / chunksize).ceil
dest << self[i, chunksize]
i += chunksize
end
dest
end
end
This feels long and not very ruby-ish, but I’m still pretty new to Ruby. Feel free to edit as you see fit.
If you’re using Rails (this won’t work in plain ruby until 1.9) you can use _in_groups_of_
src = [1, 2, 3, 4, 5]
dest = []
src.in_groups_of(2) {|n| dest << n}