How do I refer to a nested ruby hash?

115 views Asked by At

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?

3

There are 3 answers

0
Perry Horwich On

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.

0
Daniel Sindrestean On
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]

0
Ritesh Choudhary On

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"]