是否可以在 ruby​​ 中为 to_yaml 指定格式选项? [英] Is it possible to specify formatting options for to_yaml in ruby?

查看:33
本文介绍了是否可以在 ruby​​ 中为 to_yaml 指定格式选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码

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

生产

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

虽然这是一个正确的 yaml,但当你有一个数组散列时它看起来很难看.有没有办法让 to_yaml 生成 yaml 的内联数组版本?

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?

可以将选项哈希传递给 to_yaml 但是你如何使用它?

编辑 0:感谢 Pozsár Balázs.但是,从 ruby​​ 1.8.7 (2009-04-08 patchlevel 160) 开始,选项哈希不能像宣传的那样工作.:(

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

推荐答案

这个丑陋的 hack 似乎可以解决问题...

This ugly hack seems to do the trick...

class Array
  def to_yaml_style
    :inline
  end
end

浏览 ruby​​ 的源代码,我找不到任何我可以通过的选项来实现相同的目标.lib/yaml/constants.rb 中描述了默认选项.

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.

这篇关于是否可以在 ruby​​ 中为 to_yaml 指定格式选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆