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
About the hash options: see http://yaml4r.sourceforge.net/doc/page/examples.htm
Ex. 24: Using to_yaml
with an options Hash
puts [[ 'Crispin', 'Glover' ]].to_yaml( :Indent => 4, :UseHeader => true, :UseVersion => true )
# prints:
# --- %YAML:1.0
# -
# - Crispin
# - Glover
Ex. 25: Available symbols for an options Hash
Indent
: The default indentation to use when emitting (defaults to2
)Separator
: The default separator to use between documents (defaults to'---'
)SortKeys
: Sort Hash keys when emitting? (defaults tofalse
)UseHeader
: Display the YAML header when emitting? (defaults tofalse
)UseVersion
: Display the YAML version when emitting? (defaults tofalse
)AnchorFormat
: A formatting string for anchor IDs when emitting (defaults to 'id%03d
')ExplicitTypes
: Use explicit types when emitting? (defaults tofalse
)BestWidth
: The character width to use when folding text (defaults to80
)UseFold
: Force folding of text when emitting? (defaults tofalse
)UseBlock
: Force all text to be literal when emitting? (defaults tofalse
)Encoding
: Unicode format to encode with (defaults to:Utf8
; requires Iconv)
Starting from Ruby 1.9 psych
is used as a default YAML engine. It supports some attributes: http://ruby-doc.org/stdlib-2.1.0/libdoc/psych/rdoc/Psych/Handler/DumperOptions.html
So for me it works:
irb(main):001:0> require 'yaml'
=> true
irb(main):002:0> puts [{'a'=> 'b', 'c'=> 'd'}, {'e'=> 'f', 'g'=>'h'}].to_yaml(:indentation => 4)
---
- a: b
c: d
- e: f
g: h
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With