I would like to display data in Columns rather than Rows in my web page.
What is the most efficient way to do this using Ruby on Rails?
Many thanks for your
Here's my solution. It takes an array, say ["a", "b", "c", "d"] and converts it into this array: [["a", "b"], ["c"], ["d"]] which is then easy to use to display data in columns.
def categories_in_columns(categories, number_of_groups=3)
groups = []
elements_per_column = categories.size / number_of_groups
extra_elements = categories.size % number_of_groups
has_extra_elements = (extra_elements > 0 ? 1 : 0)
0.upto(number_of_groups-1).each do |i|
groups[i] = []
while groups[i].size < (elements_per_column + has_extra_elements)
groups[i] << categories.shift
extra_elements -= 1 if groups[i].size > elements_per_column
end
has_extra_elements = 0 if extra_elements == 0
groups[i].compact!
end
groups.delete_if { |i| i.empty? }
end
And specs for it:
it "arranges categories into columns" do
categories_in_columns(["a", "b", "c", "d", "e"]).should == [["a", "b"], ["c", "d"], ["e"]]
categories_in_columns(["a", "b", "c", "d"] ).should == [["a", "b"], ["c"], ["d"]]
categories_in_columns(["a", "b", "c"] ).should == [["a"], ["b"], ["c"]]
categories_in_columns(["a", "b"] ).should == [["a"], ["b"]]
categories_in_columns(["a"] ).should == [["a"]]
end