[英]How do I refer to a nested ruby hash?
我有一個 yaml 文件 tasks.yml 聲明一個 hash 因此:
"Place1 8a-5p":
type: "W"
abbr: "w"
"SpotX 7:00a-4:00p":
type: "W"
abbr: "w"
"AnotherSpot7-4":
type: "N"
abbr: "-"
Hash 的漂亮打印如下所示:
{"Place1 8a-5p"=>{"type"=>"W", "abbr"=>"w"},
"SpotX 7:00a-4:00p"=>{"type"=>"W", "abbr"=>"w"},
"AnotherSpot7-4"=>{"type"=>"N", "abbr"=>"-"}}
當我嘗試引用這樣的鍵時:
tasks = YAML.load(File.read("tasks.yml"))
puts tasks.first["type"]
我收到此錯誤:
`[]': 沒有將字符串隱式轉換為 Integer (TypeError)
如果我使用,我會看到同樣的錯誤:
puts tasks.first[:type]
如何引用此 hash 的類型和縮寫鍵?
tasks.first[1]["type"]
公元前
Enumerable#first 方法返回添加到 hash 的第一個鍵/值對作為兩個項目的數組 [key, value]
您可以使用此獲取類型
tasks.values.first["type"]
=> "W"
如果你想要類型鍵列表,那么你可以使用下面的代碼
tasks.values.collect{|v| v["type"]}
=> ["W", "W", "N"]
我試圖這樣做:
tasks.each do |k,v|
if v["type"] == "W" or v["type"] == "N"
weekendTasks << k
end
end
現在工作。
https://stackoverflow.com/users/386540/ritesh-choudhary 提示我直接使用“值”
https://stackoverflow.com/users/3449508/daniel-sindrestean讓我知道每個任務都包含一組鍵/值對
不止一個正確答案。 謝謝你們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.