Reputation:
I have:
hash = {key1: "value1", key2: {key3: "value2", key4: "value3"}}
My goal is to access the values of key3
and key4
.
My code is:
hash.each do |key, value|
puts key
value.each do |k, v|
puts k
puts v
end
end
I get an output with error:
key1
NoMethodError: undefined method `each' for "value1":String
Can someone explain what is going on, and why I am getting this error?
Upvotes: 1
Views: 4421
Reputation: 6121
{key1: "value1", key2: {key3: "value2", key4: "value3"}}
Your hash is not consistent hash of hashes, in the first iteration, value
is value1
which is a string, and you cannot iterate over a string
.
to avoid that, you can check beforehand like,
hash.each do |key,value|
p key
if value.is_a?(Hash)
value.each do |k,v|
p k
p v
end
else
p value
end
end
My goal is to access the values of key3 and key4. (I want to put them in a variable of some kind to be used elsewhere)
you can traverse a hash based on key associations. As per your need above, you can simply do:
hash[:key2][:key3]
#=> "value2"
hash[:key2][:key4]
#=> "value3"
Upvotes: 2