user2161474
user2161474

Reputation:

three column ordered list

i have a list of categories that i'd like to show in 3 columns ordered by name. I am using ul and li with css

li {
  float: left;
  width: 33%;
}

so I can just loop through each categories. This is working fine except for one issue, ordering. I'd like the list ordered alphabetically but by column. To demonstrate, if I have 7 categories, A to G, it currently looks like

A  |  B  |  C
D  |  E  |  F
G  |

I'd like it to look like

A  |  D  |  G  
B  |  E  |
C  |  F  |

Is there a way to achieve this?

Upvotes: 2

Views: 126

Answers (3)

tokland
tokland

Reputation: 67850

xs = %w(a b c d e f g)
xs.in_groups(3).transpose
#=> [["a", "d", "g"], ["b", "e", nil], ["c", "f", nil]]

And now that the row elements are nicely placed, draw the table.

Upvotes: 1

Ganesh Kunwar
Ganesh Kunwar

Reputation: 2653

@array = [A..Z]  
$i = 0
$j = 0 
    while $i < $array.count  do
     <ul>
       while $j < 3
      <li>
        puts @array[$i]
      </li>
        $j +=1
       end
       $i +=1
     </ul>
    end

Use this concept of nested while loop.

Upvotes: 0

jvnill
jvnill

Reputation: 29599

There are 2 ways to go over this. Both involves grouping your list in 3 groups which can be achieved using in_groups_of but you need to pass the number of elements that should belong in the group

@categories = ('A'..'G').to_a

total_per_column = (@categories.size / 3.0).ceil
@categories = @categories.in_groups_of(3, false)

You need to pass false so it won't try to fill up the missing elements, ie the last group will only contain 'G'

Next are the two options:

  1. use 3 ul that are floated left

    <% @categories.each do |categories| %>
      <ul>
       <% categories.each do |category| %>
         <li><%= category %></li>
       <% end %>
      </ul>
    <% end %>
    
  2. or use some sort of logic like below

    <ul>
      <% total_per_column.times do |index| %>
        <% @categories.each do |categories| %>
          <% if category = categories[index] %>
            <li><%= category %></li>
          <% end %>
        <% end %>
      <% end %>
    </ul>
    

I personally prefer the first one because it's simpler. :)

Upvotes: 2

Related Questions