ruby-on-rails – 使用类似的键加载和生成Yaml文件

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用类似的键加载和生成Yaml文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个具有类似键的yaml文件文件

sample_file.yml

line:
  title: line-name
  department: transcription

  input_formats:
    - input_format:
        name: company
        required: true
        valid_type: general
    - input_format:
        name: website
        required: false
        valid_type: url

生成new_file.yml之后,按字母顺序排列按键:

new_file.yml

line: 
  department: transcription
  input_formats: 
    - 
      input_format: 
      name: company
      required: true
      valid_type: general
    - 
      input_format: 
      name: website
      required: false
      valid_type: url

  title: line-name

打开sample_file并创建new_file的代码如下:

require 'yaml'
require 'ya2yaml'


@file = YAML::load(File.open("/Users/manish/Desktop/yaml/sample_file.yml"))
@new_file = File.new("/Users/manish/Desktop/yaml/new_file.yml","w+") 
@new_file.syswrite(@file.ya2yaml(:hash_order => ['title','department','input_formats']))

我使用“ya2yaml”gem来生成yaml文件.为了获得与sample_file.yml中相同的顺序,我在这里使用了hash_order @ new_file.syswrite(@ file.ya2yaml(:hash_order => [‘title’,’department’,’input_formats’])),但它不工作.我如何保留订单?

解决方法

最后我得到了订购问题的解决方案.
:hash_order只适用于顶级哈希.所以它只有当我从我的sample_file.yml中删除“行”键时才有效.然后订单被保留. : –
title: line-name
department: transcription

input_formats:
  - input_format:
      name: company
      required: true
      valid_type: general
  - input_format:
      name: website
      required: false
      valid_type: url
原文链接:https://www.f2er.com/ruby/266520.html

猜你在找的Ruby相关文章