Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

yaml - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...