Marnen Laibow-Koser wrote:
> [...]
>> ## Column-wise is a bit more work
>> 
>> irb> row_count = (array.length + (3-1))/3
>> => 5
>> irb> columns = []
>> => []
> [...]
> 
> Why go to all that trouble?  in_groups and zip.  Done.  No arithmetic.
> 
> Best,
> --
> Marnen Laibow-Koser
> http://www.marnen.org
> [email protected]

That really depends on what the desired output is. The OP indicated that 
he was looking for a phone book style sorting, top-to-bottom, 
left-to-right.

> It currently sorts my categories as below:
>
> | Category1 Category2 Category3 | Category4 Category5 Category6 |
>
> This is not what I want. What I want is:
>
> | Category1 | Category4 |
> | Category2 | Category5 |
> | Category3 | Category6 |

in_groups doesn't do exactly that. Here is an example:

Given a = [1,2,3,4,5,6,7,8,9] and I want the output to be

1 6
2 7
3 8
4 9
5

>> a = [1,2,3,4,5,6,7,8,9]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

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

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

Here is a method that was constructed back in the Rails 1.2 days [1]:

def in_vertical_groups_of(number, fill_with = nil, &block)
  return in_groups_of((size.to_f / number).ceil, fill_with, 
&block).transpose
end

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

I add this to something that is in config/intializers

module ActiveSupport
  module CoreExtensions
    module Array
      module Grouping
        def in_vertical_groups_of
        end
      end
    end
  end
end

Peace,
Phillip

[1] original thread: http://www.ruby-forum.com/topic/137230
-- 
Posted via http://www.ruby-forum.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 [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to