保留从 Ruby 中的文件加载 YAML 的关键顺序
我想保留从磁盘加载的 YAML 文件中键的顺序,以某种方式处理并写回磁盘。
以下是在 Ruby (v1.8.7) 中加载 YAML 的基本示例:
require 'yaml'
configuration = nil
File.open('configuration.yaml', 'r') do |file|
configuration = YAML::load(file)
# at this point configuration is a hash with keys in an undefined order
end
# process configuration in some way
File.open('output.yaml', 'w+') do |file|
YAML::dump(configuration, file)
end
不幸的是,一旦构建了哈希,这将破坏 configuration.yaml
中键的顺序。我找不到控制 YAML::load()
使用什么数据结构的方法,例如 alib 的 orderedmap
。
我没有运气在网上搜索解决方案。
I want to preserve the order of the keys in a YAML file loaded from disk, processed in some way and written back to disk.
Here is a basic example of loading YAML in Ruby (v1.8.7):
require 'yaml'
configuration = nil
File.open('configuration.yaml', 'r') do |file|
configuration = YAML::load(file)
# at this point configuration is a hash with keys in an undefined order
end
# process configuration in some way
File.open('output.yaml', 'w+') do |file|
YAML::dump(configuration, file)
end
Unfortunately, this will destroy the order of the keys in configuration.yaml
once the hash is built. I cannot find a way of controlling what data structure is used by YAML::load()
, e.g. alib's orderedmap
.
I've had no luck searching the web for a solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 Ruby 1.9.x。以前版本的 Ruby 不保留哈希键的顺序,但 1.9 则保留。
Use Ruby 1.9.x. Previous version of Ruby do not preserve the order of Hash keys, but 1.9 does.
如果您出于某种原因而无法使用 1.8.7(就像我一样),我会求助于使用
active_support/ordered_hash
。我知道activesupport
似乎是一个很大的包含,但他们在以后的版本中将其重构为您几乎只需要文件中需要的部分,而其余部分则被忽略。只需gem install activesupport
,并包含它,如下所示。另外,在 YAML 文件中,请务必使用 !!omap 声明(和哈希数组)。举例时间!这是它背后的 Ruby 的样子。
我正在寻找一种解决方案,允许我递归地挖掘从
.yml
文件加载的Hash
,查找那些YAML::PrivateClass
对象,并将它们转换为ActiveSupport::OrderedHash
。我可能会就此提出问题。If you're stuck using 1.8.7 for whatever reason (like I am), I've resorted to using
active_support/ordered_hash
. I knowactivesupport
seems like a big include, but they've refactored it in later versions to where you pretty much only require the part you need in the file and the rest gets left out. Justgem install activesupport
, and include it as shown below. Also, in your YAML file, be sure to use an !!omap declaration (and an array of Hashes). Example time!Here's what the Ruby behind it looks like.
I'm looking for a solution that allows me to recursively dig through a
Hash
loaded from a.yml
file, look for thoseYAML::PrivateClass
objects, and convert them into anActiveSupport::OrderedHash
. I may post a question on that.有人提出了同样的问题。有一个 gem 有序哈希。请注意,它不是哈希,它创建哈希的子类。您可以尝试一下,但如果您发现处理 YAML 时出现问题,那么您应该考虑升级到 ruby1.9。
Someone came up with the same issue. There is a gem ordered hash. Note that it is not a hash, it creates a subclass of hash. You might give it a try, but if you see a problem dealing with YAML, then you should consider upgrading to ruby1.9.