Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR show elements in two columns

how can i split elements of a model into two equally sized pieces so that i can show them in two columns?

i have this:

element 1
element 2
element 3
element 4
element 5


and i want this:

element 1    element 4
element 2    element 5
element 3

split() unfortunately removes the middle element.

like image 560
Patrick Oscity Avatar asked Nov 25 '09 17:11

Patrick Oscity


2 Answers

Array#in_groups_of is an core extension and only available in Rails. What it uses though is the each_slice method.

You could use it like this:

a = ["element 1", "element 2", "element 3", "element 4", "element 5"]
a.each_slice((a.size/2.0).ceil) { |slice| puts slice } if a.size > 0

will give you

["element 1", "element 2", "element 3"]
["element 4", "element 5"]

Note that you must check that a.size is bigger then 0 or you will get an ArgumentError exception due to invalid slice size.

like image 146
mrD Avatar answered Sep 28 '22 17:09

mrD


as i only need to use this in rails, this worked for me:

>> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> a.in_groups_of( (a.size/2.0).ceil, false ) if a.size > 0
=> [[1, 2, 3], [4, 5]]
like image 44
Patrick Oscity Avatar answered Sep 28 '22 19:09

Patrick Oscity