On May 28, 2010, at 9:47 AM, Pale Horse wrote:

I want to split a single array into 3 columns of equal (or as near to as
possible) length. What would you advise I do?

Well, that depends on whether you want the elements to flow row-wise or column-wise.

irb> require 'enumerator'
=> true
irb> array = %w[ a b c d e f g h i j k l m n ]
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]

## Row-wise is easy

irb> array.each_slice(3) do |a,b,c|
       puts [a,b,c]*'  '
     end
a  b  c
d  e  f
g  h  i
j  k  l
m  n
=> nil

## Column-wise is a bit more work

irb> row_count = (array.length + (3-1))/3
=> 5
irb> columns = []
=> []
irb> array.each_slice(row_count) do |col|
       columns << col
       columns[-1] << nil while columns[-1].length < row_count
     end
=> nil
irb> columns.transpose.each do |a,b,c|
       puts [a,b,c]*'  '
     end
a  f  k
b  g  l
c  h  m
d  i  n
e  j
=> [["a", "f", "k"], ["b", "g", "l"], ["c", "h", "m"], ["d", "i", "n"], ["e", "j", nil]]

Enjoy!

-Rob

Rob Biedenharn
http://agileconsultingllc.com
        r...@agileconsultingllc.com
http://gaslightsoftware.com
        r...@gaslightsoftware.com

--
You received this message because you are subscribed to the Google Groups "Ruby on 
Rails: Talk" group.
To post to this group, send email to rubyonrails-t...@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to