Reputation: 2846
I have a yaml file tasks.yml that declares a hash thus:
"Place1 8a-5p":
type: "W"
abbr: "w"
"SpotX 7:00a-4:00p":
type: "W"
abbr: "w"
"AnotherSpot7-4":
type: "N"
abbr: "-"
pretty print of Hash looks like this:
{"Place1 8a-5p"=>{"type"=>"W", "abbr"=>"w"},
"SpotX 7:00a-4:00p"=>{"type"=>"W", "abbr"=>"w"},
"AnotherSpot7-4"=>{"type"=>"N", "abbr"=>"-"}}
When I try to reference a key like this:
tasks = YAML.load(File.read("tasks.yml"))
puts tasks.first["type"]
I get this error:
`[]': no implicit conversion of String into Integer (TypeError)
I see the same error if I use:
puts tasks.first[:type]
How do I reference the type and abbr keys for this hash?
Upvotes: 0
Views: 110
Reputation: 1193
tasks.first[1]["type"]
Bcs
Enumerable#first method returns the first key/value pair that was added to the hash as an Array of two items [key, value]
Upvotes: 2
Reputation: 2846
I was trying to do this:
tasks.each do |k,v|
if v["type"] == "W" or v["type"] == "N"
weekendTasks << k
end
end
Which now works.
https://stackoverflow.com/users/386540/ritesh-choudhary clued me in to using 'values' directly
https://stackoverflow.com/users/3449508/daniel-sindrestean clued me in to the fact that each task contains an array of key/value pairs
More than one correct answer. Thank you all.
Upvotes: 0
Reputation: 782
You can get type by using this
tasks.values.first["type"]
=> "W"
if you want list of type key then you can get using below code
tasks.values.collect{|v| v["type"]}
=> ["W", "W", "N"]
Upvotes: 2