The Options Hash

Whether you're parsing or emitting YAML, you'll likely use an options hash to tell YAML.rb how to handle data. Most YAML.rb functions can take an options hash as their final parameter. For example, the to_yaml method from the previous chapters can accept an options hash:

puts [[ 'Crispin', 'Glover' ]].to_yaml( :Indent => 4, :UseHeader => true, :UseVersion => true )
# prints:
#   --- %YAML:1.0
#   -
#       - Crispin
#       - Glover
Ex. 24: Using to_yaml with an options Hash

As you can see, the options hash consists of key/value pairs which affect the output of to_yaml. When parsing, many of these options are set when a YAML document is loaded. For example, when the above YAML document is loaded by YAML::load_stream, the version number and the indent will be used to set the default options for the loaded YAML::Stream object. In an options hash, the key is a symbol, selected from any of the option symbols listed below:

Indent: The default indentation to use when emitting (defaults to 2)
Separator: The default separator to use between documents (defaults to '---')
SortKeys: Sort Hash keys when emitting? (defaults to false) 
UseHeader: Display the YAML header when emitting? (defaults to false)
UseVersion: Display the YAML version when emitting? (defaults to false)
AnchorFormat: A formatting string for anchor IDs when emitting (defaults to 'id%03d')
ExplicitTypes: Use explicit types when emitting? (defaults to false)
BestWidth: The character width to use when folding text (defaults to 80)
UseFold: Force folding of text when emitting? (defaults to false)
UseBlock: Force all text to be literal when emitting? (defaults to false)
Encoding: Unicode format to encode with (defaults to :Utf8; requires Iconv)
Ex. 25: Available symbols for an options Hash

See the YAML Module Reference later in this manual for any of the following functions which all can receive an options hash:

any Object#to_yaml method
YAML::Stream.new
YAML::Store.new
YAML::emitter_proc
Ex. 26: Methods which take an options Hash