如何从Ruby数组输出指定格式的HTML?

时间:2011-09-24 14:03:34

标签: html ruby

我有各种食品,如下:

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

现在,我知道如何在Ruby中获取数组中所有元素的HTML列表。我可以这样做:

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

但是,我不知道如何将列表分成每个字母的不同部分,这样我就可以获取这个数组并输出一堆单独的项目列表(用HTML格式),如下所示:

<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>
    ...

我如何在Ruby中创建此输出?

2 个答案:

答案 0 :(得分:2)

您可以使用Enumerable#group_by按第一个字符对值进行分组,如下所示:

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

尽管如此,这并不会将所有食物都以一个数字开头。这需要更多的魔力:

    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
    }

答案 1 :(得分:0)

您可以先在输入列表中执行group_by

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

然后像以前一样继续。

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