Reputation: 29
I am trying to access a value from an array of hash. An example array looks like this:
family = [
[
{ "Homer" => 1, "Marge" => 2, "Lisa" => 3, "Maggie" => 4,
"Abe" => 5, "Santa's Little Helper" => 6
}
],
[
{ "Homer" => 2, "Marge" => 4, "Lisa" => 6,
"Maggie" => 8, "Abe" => 10, "Santa's Little Helper" => 12
}
]
]
If I try to access the hash value for key "Homer"
in array indexed 0
(family[0]
) using the statement below and hoping to get the value 1
:
family[0]["Homer"]
I get an error which says
"test.rb:4:in `[]': can't convert String into Integer (TypeError)"
Any suggestions on how one might be able to access a hash value in such an array, in a simple statement?
Upvotes: 0
Views: 16935
Reputation: 118299
You should try family[0][0]["Homer"]
.
In your case family[0]
gives you :
[{ "Homer" => 1, "Marge" => 2, "Lisa" => 3, "Maggie" => 4, "Abe" => 5,"Santa Little Helper" => 6}]
which is an array. The hash you want is inside it and can be got with family[0][0]
:
{ "Homer" => 1, "Marge" => 2, "Lisa" => 3, "Maggie" => 4, "Abe" => 5,"Santa Little Helper" => 6}
So you can now use family[0][0]["Homer"]
which will give you the value 1
.
The array indices are always numeric values. If you get a can't convert String into Integer (TypeError)
error message an exception is thrown because you are trying to access array element using a string that can't be converted to an integer.
Upvotes: 8
Reputation: 2073
@Arup Rakshit is absolutely correct about how to get your value. But you should also know that you don't have an array of hashes, you have an array of arrays, and those sub-arrays contain hashes. Based on your title I'm concluding that you probably want a structure more like
family = [
{ "Homer" => 1, "Marge" => 2, "Lisa" => 3, "Maggie" => 4,
"Abe" => 5, "Santa's Little Helper" => 6
},
{ "Homer" => 2, "Marge" => 4, "Lisa" => 6,
"Maggie" => 8, "Abe" => 10, "Santa's Little Helper" => 12
}
]
Upvotes: 1
Reputation: 61540
You don't actually have an array of hashes. You have an array of arrays of hashes.
Your error occurs because you dereference your structure with [0]
which gives you the first array of hashes, now you try to access the key 'homer'
which doesnt exist because arrays are keyed by integers.
Here is an example of how you could see all of the values, see if you can get 'homer'
on your own:
family.each do |a| # this is an array of arrays of hashes
a.each do |h| # this is an array of hashes
h.each do |k,v| # this is a hash
puts "#{k} => #{v}"
end
end
end
Output:
Homer => 1
Marge => 2
Lisa => 3
Maggie => 4
Abe => 5
Santa's Little Helper => 6
Homer => 2
Marge => 4
Lisa => 6
Maggie => 8
Abe => 10
Santa's Little Helper => 12
Upvotes: 1