代码

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

产生

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

虽然这是一个正确的其,它只是相貌丑陋的时候你有的散列阵列。有没有办法为我得到 to_yaml 产生的内联阵版本的其?

一个选项的散列可以通过来 to_yaml 但你如何使用它?

编辑0:谢谢Pozsár巴拉兹.但是,正如红宝石1.8.7(2009-04-08补160),该项散列不作广告。:(

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
有帮助吗?

解决方案 2

这丑陋的黑客似乎这样的伎俩......

class Array
  def to_yaml_style
    :inline
  end
end

通过Ruby的源浏览,我无法找到我能通过来实现相同的任何选项。缺省选项是在 LIB / YAML / constants.rb描述

其他提示

关于哈希选项:请参阅 http://yaml4r.sourceforge.net/doc/页/ examples.htm

实施例。 24:使用to_yaml与选项散列

puts [[ 'Crispin', 'Glover' ]].to_yaml( :Indent => 4, :UseHeader => true, :UseVersion => true )
# prints:
#   --- %YAML:1.0
#   -
#       - Crispin
#       - Glover

实施例。 25:用于选择哈希可以使用的符号

  

Indent:默认缩进到发射(默认为2)时使用的,点击   Separator:默认分隔文档之间使用(默认为'---')点击   SortKeys:排序时发出哈希键? (默认为false),点击   UseHeader:发光时显示YAML头? (默认为false),点击   UseVersion:发光时显示YAML版本? (默认为false),点击   AnchorFormat:发射(默认为“id%03d”)当A格式化字符串锚ID的点击   ExplicitTypes:发射时,使用显式类型? (默认为false),点击   BestWidth:字符宽度折叠文本(默认为80)时使用的,点击   UseFold:强制发射时折叠的文本? (默认为false),点击   UseBlock:强制所有文字发射时是文字? (默认为false),点击   Encoding:Unicode格式与编码(默认为:Utf8;要求语言Iconv)

这红宝石1.9 psych开始被用作默认YAML发动机。它支持一些属性:的http:// ruby-doc.org/stdlib-2.1.0/libdoc/psych/rdoc/Psych/Handler/DumperOptions.html

所以对我来说它的工作原理:

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

又一个劈指定输出样式,但是这一个允许定制每特定对象,而不是全局(例如,对于所有阵列)。

https://gist.github.com/jirutka/31b1a61162e41d5064fc

简单示例:

class Movie
  attr_accessor :genres, :actors

  # method called by psych to render YAML
  def encode_with(coder)
    # render array inline (flow style)
    coder['genres'] = StyledYAML.inline(genres) if genres
    # render in default style (block)
    coder['actors'] = actors if actors
  end
end

红宝石的最新版本用于YAML解析的精极度紧张模块。有没有,你可以通过,但你可以改变缩进和线宽许多选项。检查最新的精极度紧张的文档的更多细节。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top