如何使用YAML :: Store将哈希中的数组保存到单行yaml序列中

时间:2019-01-16 07:19:38

标签: ruby yaml

我正在使用YAML::Store以易于阅读的形式保存数据。

require 'yaml/store'
db = YAML::Store.new("db.yaml")

传递给yaml存储的数据是哈希。一些值是大数组。代码示例:

hash = {"foo" => "bar", "array" => [1,2,3,4,5,6,7,8,9]}
db.transaction do
  db["1"] = hash
end

Yaml存储使用破折号保存数组,其中每个值都在换行符中。 Yaml数据库看起来像是一列庞大的数字。看起来像这样:

---
'1':
  foo: bar
  array:
  - 1
  - 2
  - 3
  - 4
  - 5
  - 6
  - 7
  - 8
  - 9

它可以正常工作,但是却失去了可读性。我希望Yaml看起来像这样:

---
'1':
  foo: bar
  array: [1,2,3,4,5,6,7,8,9]

有没有一种方法可以将数组保存在一行中?

编辑:我看到存在hash.to_yaml的选项,但是如何将它们实现到yaml :: store中。 这就是文档所说的:

initialize( file_name, yaml_opts = {} )

无法使其正常工作。例如,这不会改变任何东西:

yaml_opts = { :Indent => 50 }
db = YAML::Store.new("db.yaml", yaml_opts)

0 个答案:

没有答案