2016-07-16 38 views
0

所以我有這樣的測試腳本轉`YAML :: load_file`到合適的哈希

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

乾杯,

回答

0

所以我發現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 

乾杯,

+0

可能值得注意的是,反函數'YAML :: load',這是'YAML :: dump'輸出':鍵:itsValue' Yaml會議。這將推動第一個解決方案:編輯源Yaml文件,以便它包含':key:itsValue'賦值 – marsupilam