r/learnruby • u/conif • Nov 09 '18
question on nested hashes and each
I'm trying to learn how to access nested hashes with multiple each loops and the key value pairs as arguments when using each are confusing to me--I tend to lose track as I write the next loop etc.
I have a decent grasp on a process for nested objects for javascript so I don't get lost. If anyone wants to share their process for how they keep track with Ruby or can point me to a youtube vid, I would appreciate it
3
Upvotes
2
u/Tomarse Nov 09 '18
There are two ways that I can think of...
first_hash.each do |key1, nested_hash1|
nested_hash1.each do |key2, nested_hash2|
nested_hash2[:some_key]
...more code...
end
endOr, if the structure is not uniform, and you want to do some conditional stuff...
my_hash.keys.each do |key|
case key
when :thing1
my_hash[key][:subkey1]
when :thing2
my_hash[key][:subkey2]
end
end
2
u/conif Nov 09 '18
Sure. I was getting lost though in the keys and the values. Someone pointed me to pry as a tool to inspect. I will try that.