Oct 8 2009

Jamming with Ruby YAML

When working with Ruby, the library/class I use and abuse most often is YAML. YAML stands for YAML Ain’t Markup Language and it is a versatile human friendly data serialization format. It is easier to use and understand than JSON.

A YAML file is much like a Java properties file in that is used to store name/value pairs. YAML is more powerful than simple Java properties file but that is a good way to think of it to begin with. Here is a example of a simple YAM file used to store user name and password.

user: juixe-username
pass: juixe-password

The above YAML snippet can go into a file, typically with a yml extension. To load the YAML file in ruby you can do it in with following Ruby code.

require 'yaml'

yml = YAML::load(File.open('userinfo.yml'))
puts yml['user'] # juixe-username

Just replace userinfo.yml with the name and path of your YAML file. The object that is loaded from the YAML file is a regular Ruby hash object so you can iterate through all the name/value pairs like the following.

require 'yaml'

yml = YAML.load_file 'userinfo.yml'
yml.each_pair { |key, value|
  puts "#{key} = #{value}"

What makes YAML files more powerful than a regular Java properties file is that you can complex object collections, structures, or hierarchies. For example, imagine that I want to log into a series of Twitter accounts and get their most recent at replies. I can keep a collection of twitter account usernames and passwords in a YAML file much like the following.

 user: juixe-user
 pass: juixe-pass
 user: techknow-user
 pass: techknow-pass

Here is the sample Ruby code that can be used to iterate through each user account from the YAML file.

require 'yaml'

yml = YAML.load_file 'userinfo.yml'
yml.each_key { |key|
  username = yml[key]['user']
  password = yml[key]['pass']

  puts "#{username} => #{password}"
  # login ...

You build more complex data structures than this using YAML, but this should be enough to get you going.