views:

176

answers:

5

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.

+1  A: 

Check out Array#in_groups_of

This will slice an array in chunks of your liking.

Alexander Malfait
A: 

One approach is to use jQuery. There are several plugins that can accomplish this for you.

Subsequently, after you have the two chunks, start filling up a div with the first group, once you get to the end, start the second group in a second div. Then use css to position and style the two divs beside one another.

Chris Johnston
+3  A: 

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.

mrD
if it's only available in rails, it's perfectly fine.
padde
Nice call on checking for the size being > 0. That bit me today, thanks!
Daniel Huckstep
A: 

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]]
padde
A: 

Where are you trying to show these elements?

If it's in a view, you should not be modifying your model; your models should stay independent from your presentation.

If you want to present results on a web page, you must use html and css in your view. Even in your view, you probably won't need to "split" your elements into sub arrays.

See this page, for example. If you look at the source code, the lists are allways "one after the other", without splitting into groups. The CSS conditions how the text is positioned.

egarcia
the page is a bad example because it doesnt lead to the desired order if you recall the code block in my question. i am trying to put each part of the array into an instance variable that is then passed to the view and displayed. or is there a better way?
padde
Hi patrick, I don't understand why you say that the order isn't conserved. If you have the array like [1,2,3,4] your html items will be <li>1</li> <li>2</li> <li>3</li> etc. You will only have to pass that variable to the view, and it will render it in two columns using css. I see no need of two variables.
egarcia