【问题标题】:turn `YAML::load_file` into proper hash将 `YAML::load_file` 转换为正确的哈希
【发布时间】:2016-11-19 15:00:33
【问题描述】:

所以我有这个测试脚本

require 'yaml'

hashYaml = YAML::load_file("./monFichier.yaml")
puts "hashYaml : " 
puts hashYaml

hashManuel = {enonce: "ma question", titre: "mon titre" } 
puts "hashManuel : "
puts hashManuel

./monFichier.yaml 包含以下行:

- enonce: "ma question"
  titre: "mon titre" 

输出是:

hashYaml : 
{"enonce"=>"ma question", "titre"=>"mon titre"}
hashManuel : 
{:enonce=>"ma question", :titre=>"mon titre"}

谁能解释一下

  1. 为什么两条线不同?
  2. 如何获得与hashManuel 格式相同的hashYaml

干杯,

【问题讨论】:

    标签: ruby yaml


    【解决方案1】:

    所以我找到了this answer,我检查它正在工作。

    就是编辑Yaml文件如下:

    - :enonce: "ma question"
      :titre: "mon titre" 
    

    还有其他不涉及修改我的 yaml 文件的方法吗? 是的,见下文

    编辑:我一直在寻找的答案

    改编自this post

    所以我的 Yaml 文件在 Ruby 中定义了一个哈希表。说,上面写着:

    - enonce: "ma question facile"
      titre: "mon titre clair" 
    - enonce: "ma question dure"
      titre: "mon titre obscur" 
    

    在 Ruby 中将此文件作为键为符号的哈希列表导入,即{:myKey => "itsValue"} (在我知道词汇之前,我的意思是正确的哈希 可以如下进行:

    require 'yaml'
    
    hashYaml = YAML::load_file('./monFichier.yaml')
    
    hashYaml.each do |currentHash| # I am really working with a table of hash(es)
      currentHash.keys.each do |key|
        currentHash[(key.to_sym rescue key) || key] = currentHash.delete(key)
      end
    end
    

    干杯,

    【讨论】:

    • 可能值得注意的是,YAML::load 的反函数,即 YAML::dump 在 Yaml 中输出 :key: itsValue 约定。这将推动第一个解决方案:编辑源 Yaml 文件,使其包含:key: itsValue assignments
    猜你喜欢
    • 2013-07-08
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2019-05-23
    • 2014-04-30
    • 2017-12-22
    相关资源
    最近更新 更多