
这是在Ruby中加载YAML的基本示例(v1.8.7):
@H_301_13@require 'yaml'configuration = nilfile.open('configuration.yaml','r') do |file| configuration = YAML::load(file) # at this point configuration is a hash with keys in an undefined orderend# process configuration in some wayfile.open('output.yaml','w+') do |file| YAML::dump(configuration,file)end不幸的是,一旦构建了哈希,这将破坏configuration.yaml中键的顺序.我找不到控制YAML :: load()使用什么数据结构的方法,例如alib的有序图.
我没有运气在网上寻找解决方案.
解决方法 如果你因为任何原因(比如我)而使用1.8.7,我已经使用了active_support / ordered_hash.我知道activesupport似乎是一个很大的包含,但是他们在以后的版本中重构了它,你几乎只需要文件中需要的部分,其余部分被遗漏.只需宝石安装activesupport,并将其包含如下所示.此外,在您的YAML文件中,请务必使用!! omap声明(以及哈希数组).示例时间! @H_301_13@# config.yml #months: !!omap - january: enero - february: febrero - march: marzo - april: abril - may: mayo这是它背后的Ruby的样子.
@H_301_13@# loader.rb #require 'yaml'require 'active_support/ordered_hash'# Load up the file into a Hashconfig = file.open('config.yml','r') { |f| YAML::load f }# So long as you specifIEd an !!omap,this is actually a# YAML::PrivateClass,an array of Hashesputs config['months'].class# Parse through its value attribute,stick results in an OrderedHash,# and reassign it to our hashordered = ActiveSupport::OrderedHash.newconfig['months'].value.each { |m| ordered[m.keys.first] = m.values.first }config['months'] = ordered我正在寻找一种解决方案,允许我递归地挖掘从.yml文件加载的Hash,查找那些YAML :: PrivateClass对象,并将它们转换为ActiveSupport :: OrderedHash.我可以发一个问题.
@H_301_0@ 总结以上是内存溢出为你收集整理的保留从Ruby中的文件加载YAML的密钥顺序全部内容,希望文章能够帮你解决保留从Ruby中的文件加载YAML的密钥顺序所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)