我如何遍历此哈希数组以接收特定值:RUBY

how can I iterate through this array of hashes to receive a particular value : RUBY

我的哈希如下:

aoh=[
  { "name": "Vesper",
    "glass": "martini",
    "category": "Before Dinner Cocktail",
    "ingredients": [
      { "unit": "cl",
        "amount": 6,
        "ingredient": "Gin" },
      { "unit": "cl",
        "amount": 1.5,
        "ingredient": "Vodka" },
      { "unit": "cl",
        "amount": 0.75,
        "ingredient": "Lillet Blonde" }
    ],
    "garnish": "Lemon twist",
    "preparation": "Shake and strain into a chilled cocktail glass." },
  { "name": "Bacardi",
    "glass": "martini",
    "category": "Before Dinner Cocktail",
    "ingredients": [
      { "unit": "cl",
        "amount": 4.5,
        "ingredient": "White rum",
        "label": "Bacardi White Rum" },
      { "unit": "cl",
        "amount": 2,
        "ingredient": "Lime juice" },
      { "unit": "cl",
        "amount": 1,
        "ingredient": "Syrup",
        "label": "Grenadine" }
    ],
    "preparation": "Shake with ice cubes. Strain into chilled cocktail glass." }]

我如何遍历它以获取成分(不返回名称、玻璃杯、类别等)?我还需要相同的数量迭代,但我认为它看起来就像成分的迭代。抱歉这个愚蠢的问题,我是 ruby 的新手并且已经尝试了几个小时了。

>aoh.collect { |i| i[:ingredients].collect { |g| puts g[:ingredient] } }
   Gin
   Vodka
   Lillet Blonde
   White rum
   Lime juice
   Syrup

您的示例中有一个包含两个元素的数组。这两个元素是具有 key/value 对的散列。您可以使用 #each 方法遍历数组并访问 :"ingredients" 键存储的值,如下所示:

aoh.each do |hash|
  hash[:ingredients]
end

:ingredients 键每个存储另一个哈希数组。示例哈希是:

{ "unit": "cl",
        "amount": 6,
        "ingredient": "Gin" }

然后您可以通过 hash[:ingredient] 访问 :ingredient 键下的值。最终结果如下所示:

   aoh.each do |array_element|
    array_element[:ingredients].each do |ingredient|
      ingredient[:ingredient]
    end
  end

这目前仅遍历数组和散列。如果你还想打印结果,你可以这样做:

  aoh.each do |array_element|
    array_element[:ingredients].each do |ingredient|
      puts ingredient[:ingredient]
    end
  end
#=> Gin
#   Vodka
#   Lillet Blonde
#   White rum
#   Lime juice
#   Syrup

如果想得到修改后的数组,可以使用#map (or #flat_map)。您还可以通过这样的值获取金额:

   aoh.flat_map do |array_element|
    array_element[:ingredients].map do |ingredient|
      [[ingredient[:ingredient], ingredient[:amount]]
    end
  end
#=> [["Gin", 6], ["Vodka", 1.5], ["Lillet Blonde", 0.75], ["White rum", 4.5], ["Lime juice", 2], ["Syrup", 1]]

我会提出以下建议。

aoh=[
     { "name": "Vesper",
       "ingredients": [
         { "unit": "cl", "ingredient": "Gin" },
         { "unit": "cl", "ingredient": "Vodka" }
       ],
       "garnish": "Lemon twist"
     },
     { "name": "Bacardi",
       "ingredients": [
         { "unit": "cl", "ingredient": "White rum" },
         { "unit": "cl", "ingredient": "Lime juice" }
       ],
     }
   ]

aoh.each_with_object({}) { |g,h| h[g[:name]] =
  g[:ingredients].map { |f| f[:ingredient] } }
  #=> {"Vesper"=>["Gin", "Vodka"], "Bacardi"=>["White rum", "Lime juice"]}