繁体   English   中英

如何引用嵌套的 ruby hash?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM