Array#chunk method, maybe someone will find this useful

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

<% @photos.chunk(5).each do |pc| -%> <% pc.each do |p| -%> <% end -%> <% end -%>
<%= p.nil? ? "Empty" : p.name -%>

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

Chris H. wrote:

 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

Have you ever seen each_slice?

require ‘enumerator’

[1,2,3,4,5,6,7,8].each_slice {|a,b,c| puts a,b,c}
1,2,3
4,5,6
7,8,nil


Ola B. (http://ola-bini.blogspot.com)
JvYAML, RbYAML, JRuby and Jatha contributor
System Developer, Karolinska Institutet (http://www.ki.se)
OLogix Consulting (http://www.ologix.com)

“Yields falsehood when quined” yields falsehood when quined.

Rails already has this actually:

[1,2,3,4,5,6,7,8].in_groups_of(3) => [[1, 2, 3], [4, 5, 6], [7, 8, nil]]

-Jonathan.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs