rps
rps

Reputation: 1293

How would I output HTML in the specified format from a Ruby array?

I have an array of various food items, like so:

1% milk (low fat)
100% fruit juice blend (juicy juice)
100% whole wheat bagel
100% whole wheat bread
100% whole wheat cracker (triscuit)
2% milk (reduced fat)
alfredo sauce
all-bran cereal
all-fruit preserves (no added sugar)
...
wrap sandwich (vegetables only)
wrap sandwich (vegetables, rice)
yellow cake with icing
yellow corn (corn on the cob)
zucchini bread
zucchini or summer squash

Now, I know how to get an HTML list of all the elements in the array in Ruby. I could do something like this:

puts "<ul>"
foods.each do |e|
  puts "<li>#{e}</li>"
end
puts "</ul>"

However, I don't know how to break the list into different sections for each letter, so that I can take this array and output a bunch of seperate lists of items (in HTML), like this:

<div class="grid_1">
  <h1>#.</h1>
  <ul>
    <li>1% milk (low fat)</li>
    <li>100% fruit juice blend (juicy juice)</li>
    <li>100% whole wheat bagel</li>
    <li>100% whole wheat bread</li>
    <li>100% whole wheat cracker (triscuit)</li>
    <li>2% milk (reduced fat)</li>
  </ul>
</div>
<div class="grid_1">
  <h1>A.</h1>
  <ul>
    <li>alfredo sauce</li>
    <li>all-bran cereal</li>
    <li>all-fruit preserves (no added sugar)</li>
    ...

How would I create this output in Ruby?

Upvotes: 1

Views: 200

Answers (2)

Howard
Howard

Reputation: 39177

You can first perform a group_by on your input list

foods = foods.group_by{|x|x[0]=~/[a-z]/i?x[0].upcase():'#.'}

and then proceed as before.

foods.each do |key, list|
  puts "<div class='grid_1'>"
  puts "<h1>#{key}</h1>"
  puts "<ul>"
  list.each do |e|
    puts "<li>#{e}</li>"
  end
  puts "</ul>"
  puts "</div>"
end

Upvotes: 0

rdvdijk
rdvdijk

Reputation: 4398

You could use Enumerable#group_by to group your values by the first character, like this:

    grouped_food = food.group_by { |f| f[0] }

This would not put all the food starting with a number in a separate group, though. This would take some more magic:

    grouped_food = food.group_by { |f| 
        f[0] =~ /[0-9]/ ?  # if the first character is a number
        "#." :             # group them in the '#.' group
        f[0].upcase+"."    # else group them in the 'uppercase_first_letter.' group
    }

Upvotes: 2

Related Questions