Created
January 13, 2011 22:51
-
-
Save JoshCheek/778772 to your computer and use it in GitHub Desktop.
Showing how I would handle some data by using yaml instead of an ad hoc format.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A response for http://www.ruby-forum.com/topic/866786 | |
Just showing how to use a real data format rather than try to create one on the fly, which is fragile and error prone. | |
Here is a link to yaml docs: http://ruby-doc.org/stdlib/libdoc/yaml/rdoc/index.html |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
- :category: cat1 | |
:items: | |
- item1 | |
- item2 | |
- item3 | |
- :category: cat2 | |
:items: | |
- item1 | |
- :category: cat3 | |
:items: | |
- item1 | |
- item2 | |
- item3 | |
- item4 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'yaml' | |
require 'pp' | |
data = File.open 'data.yml' do |file| | |
YAML.load file | |
end | |
pp data |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this code will get you started so you can see what the data should look like | |
require 'yaml' | |
# I'm storing it in an Array, because Hashes are unordered pre 1.9 | |
data = [ | |
{ :category => 'cat1' , :items => ['item1', 'item2', 'item3'] }, | |
{ :category => 'cat2' , :items => ['item1'] }, | |
{ :category => 'cat3' , :items => ['item1', 'item2', 'item3', 'item4'] }, | |
] | |
File.open 'data.yml' , 'w' do |file| | |
file.puts YAML.dump(data) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment