Opinionated Programmer - Jo Liss's musings on enlightened software development.

Parsing YAML 1.1 with Ruby

To parse YAML with Ruby, do not use the YAML module, use Psych (which ships with Ruby 1.9.2, though there is also a gem).

The reason is that YAML uses the unmaintained Syck library, whereas Psych uses the modern LibYAML:

>> require 'yaml'
>> YAML.load("%YAML 1.1\n---\n'test'")  # %YAML directive not supported
=> "%YAML 1.1 --- 'test'"

>> require 'psych'
>> Psych.load("%YAML 1.1\n---\n'test'")  # all good
=> "test"

P.S. Even if the YAML you are parsing is very simple, YAML silently runs into problems with escaped whitespace (“foo\ bar”), erroneously leaving the backslashes in the output. Psych handles this just fine.

P.P.S. YAML will use Psych instead of Syck as its engine if you have require 'psych' before require 'yaml' – thanks to Benoit Daloze for pointing this out. If this implicit behavior is causing pains for you, especially with Rails or Bundler, I recommend you read Matthew Kocher’s post about YAML, Psych, and Syck (and the discussion in the comments there).