1. Computing

Serialization in Ruby: YAML

By

2 of 2

Getting Deeper into Yaml

Most times, the data stored as YAML is a hash of strings. The primary use for this is for configuration data, not object store. However, it is a serialized object and is loaded as one. Let's expand our counter example and add a configuration file.


---
:file: counter
:increment: 1
:users:
  - Alice
  - Bob
  - Carol

This is a hash with three keys. The first two keys hold a string (the filename of the counter, and the amount to increment), and the final key holds a list of users. Note that the list is indented, and each element is prefixed with a - character. Here are the two primary syntax elements of YAML, the key: value hash syntax and the - Array element syntax. Just knowing these is enough for most uses of YAML.

Loading this into a Ruby program will result in a hash. There will be three keys, file, counter and users. This can then be used as the configuration for the rest of the program.

One thing you may notice in YAML files is that keys are often strings, not symbols. Symbols are only one extra character, but strings are more often used. Be aware that any hashes you may load in YAML may have string keys, instead of symbol keys.


#!/usr/bin/env ruby
require 'yaml'

conf = YAML::load( File.read('counter.yaml') )

counter = if File.exists?(conf[:file])
            YAML::load( File.read(conf[:file]) )
          else
            0
          end

puts "Counter is currently at #{counter}"
puts "incrementing to #{counter + conf[:increment]}"

counter += conf[:increment]

File.open(conf[:file],'w') do|file|
  file.puts counter.to_yaml
end

For more information on the YAML format, see the YAML Homepage.

Serialization Methods in Ruby
  1. About.com
  2. Computing
  3. Ruby
  4. Advanced Ruby
  5. Serialization
  6. Serialization in Ruby: YAML

©2014 About.com. All rights reserved.