Reputation: 301
I have an array of hashes of hashes. Here is what the structure looks like:
items = [{"Spaghetti & Meatballs"=>
{
:menu_item_name=>"Spaghetti & Meatballs",
:quantity=>192,
:category=>"delicious"}},
{"Bananas"=>
{
:menu_item_name=>"Bananas",
:quantity=>187,
:category=>"sweet"}}]
I want to do the following:
items["Bananas"]
and return the hash at bananas.
Upvotes: 0
Views: 103
Reputation: 110675
You would like items["Banana"]
to return an array of elements (hashes) of items
that have a key "Bananas". Let's consider how that would be done.
Since items.class #=> Array
we would have to define an instance method Array#[]
to do that. There's a problem, however: Array
already has the instance method Array#[], which is used like so: [1,2,3][1] #=> 2
, where the argument is the index of the array whose value is to be returned.
With the proviso that the hash's keys are not numeric, we could do the following.
class Array
alias :left_right_paren :[]
def [](x)
if x.is_a?(Integer)
left_right_paren(x)
else
find { |h| h.keys.include?(x) }
end
end
end
[1,2,3][1]
#=> 2
items["Bananas"]
#=> {"Bananas"=>{:menu_item_name=>"Bananas", :quantity=>187, :category=>"sweet"}}
All that remains is to decide whether this would be a good idea. My opinion? YUK!!
Upvotes: 1
Reputation: 20263
With:
items = [{"Spaghetti & Meatballs"=>
{
:menu_item_name=>"Spaghetti & Meatballs",
:quantity=>192,
:category=>"delicious"}},
{"Bananas"=>
{
:menu_item_name=>"Bananas",
:quantity=>187,
:category=>"sweet"}}]
Try:
items.find{|hsh| hsh.keys.first == "Bananas"}
In console:
2.3.1 :011 > items.find{|hsh| hsh.keys.first == "Bananas"}
=> {"Bananas"=>{:menu_item_name=>"Bananas", :quantity=>187, :category=>"sweet"}}
If you want, you could assign it to a variable:
bananas_hsh = items.find{|hsh| hsh.keys.first == "Bananas"}
Again, in console:
2.3.1 :012 > bananas_hsh = items.find{|hsh| hsh.keys.first == "Bananas"}
=> {"Bananas"=>{:menu_item_name=>"Bananas", :quantity=>187, :category=>"sweet"}}
2.3.1 :013 > bananas_hsh
=> {"Bananas"=>{:menu_item_name=>"Bananas", :quantity=>187, :category=>"sweet"}}
Upvotes: 1