anshul anshul - 3 months ago 15
Ruby Question

Is it possible to specify formatting options for to_yaml in ruby?

The code

require 'yaml'
puts YAML.load("
is_something:
values: ['yes', 'no']
").to_yaml


produces

---
is_something:
values:
- "yes"
- "no"


While this is a correct yaml, it just looks ugly when you have a hash of arrays. Is there a way for me to get
to_yaml
to produce the inline array version of the yaml?

An options hash can be passed to
to_yaml
but how do you use it?


Edit 0: Thanks Pozsár Balázs. But, as of ruby 1.8.7 (2009-04-08 patchlevel 160), the options hash does not work as advertised. :(

irb
irb(main):001:0> require 'yaml'
=> true
irb(main):002:0> puts [[ 'Crispin', 'Glover' ]].to_yaml( :Indent => 4, :UseHeader => true, :UseVersion => true )
---
- - Crispin
- Glover
=> nil

Answer

This ugly hack seems to do the trick...

class Array
  def to_yaml_style
    :inline
  end
end

Browsing through ruby's source, I can't find any options I could pass to achieve the same. Default options are described in the lib/yaml/constants.rb.