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.
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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With