简体   繁体   中英

Converting an Array of hashes of hashes Ruby

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.

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

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!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM