我建议两个方案,第一个将所有产品组合在一起:
products:
- name: Apple
type: Fruit
- name: Grape
type: Fruit
- name: Tomato
type: Vegetable
- name: Brocoli
type: Vegetable
另一种方案将针对每种类型的产品在组上使用
fruits:
- name: Apple
- name: Grape
vegetable:
- name: Tomato
- name: Brocoli
要实际显示这一点,您只需使用类似的内容加载 yaml 数据(如果这已经改变,请原谅我......自从我使用 yaml 已经有一段时间了):
require 'yaml'
data = YAML.load_file('data.yml')
data 本质上只是一个 ruby 哈希,因此您可以通过遍历它来显示您喜欢的任何内容。
编辑:
如果第二个选项是你想要的。尝试以下操作:
require 'yaml'
data = YAML.load_file('data.yml')
data.each do |category, products|
puts "#{category}"
products.each do |product|
puts "\t#{products}"
end
end
输出应该是:
fruits
Apple
Grape
vegetable
Tomato
Brocoli
如果要输出html,则将其修改为:
require 'yaml'
data = YAML.load_file('data.yml')
data.each do |category, products|
puts "#{category}"
puts "<ul>"
products.each do |product|
puts "<li>#{products}</li>"
end
puts "</ul>"
end
您可以看到添加 html 格式的差异非常简单,您应该能够根据需要进一步修改它。