gpt4 book ai didi

ruby - 是否可以在 ruby​​ 中为 to_yaml 指定格式选项?

转载 作者:数据小太阳 更新时间:2023-10-29 06:29:46 24 4
gpt4 key购买 nike

代码

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

产生

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

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

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

编辑 0:感谢 Pozsár Balázs。但是,从 ruby​​ 1.8.7 (2009-04-08 patchlevel 160) 开始,options hash 并不像宣传的那样工作。 :(

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

最佳答案

关于哈希选项:参见 http://yaml4r.sourceforge.net/doc/page/examples.htm

例。 24: 使用带有选项哈希的to_yaml

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

例。 25: 选项哈希的可用符号

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)

关于ruby - 是否可以在 ruby​​ 中为 to_yaml 指定格式选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1054730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com