class Array
break an array up into chunks
def chunk(size=1)
return self if self.empty?
raise ArgumentError if !size.kind_of? Integer
y = self.length.divmod(size)
rows = (y[1] > 0) ? y[0] + 1 : y[0]
arr = Array.new(rows)
(0...rows).each do |i|
arr[i] = self.slice(size*i, size)
end
(arr.last.length...size).each { |i| arr.last[i] = nil } if
arr.last.length < size
arr
end
end
put it in /lib and add require ‘array’ at the end of environment.rb
and restart and you should be good to go.
have you ever found yourself trying to loop through an activerecord
result array and determine how to handle displaying a specific # of
items per row and what to do when you have an odd number of elements
on the last row? it can get ugly.
Array.chunk might be for you.
this method takes an array and breaks it out into smaller subarrays of
a specified size.
@photos = Photo.find(:all).
say you had 12 photos returned…chunk would break your array of
photos up into ‘chunks’ of 5 elements each adding nil objects to fill
in the empty elements, so you would end up with
[[p1, p2, p3, p4, p5], [p6, p7, p8, p9, p10], [p11, p12, nil, nil, nil]]
then in your view you could do
| <%= p.nil? ? "Empty" : p.name -%> | <% end -%>
note: i’ve only done rudimentary testing by hand in irb and console.
so your mileage may vary. if it needs a license, then MIT.
Chris