0

我拥有的哈希如下:

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​​ 的新手,并且已经尝试了几个小时。

4

3 回答 3

0
>aoh.collect { |i| i[:ingredients].collect { |g| puts g[:ingredient] } }
   Gin
   Vodka
   Lillet Blonde
   White rum
   Lime juice
   Syrup
于 2020-05-07T17:05:29.870 回答
0

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

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

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

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

然后,您可以:ingredient通过执行访问键下的值hash[: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(或#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]]
于 2020-05-07T17:29:40.717 回答
-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"]} 
于 2020-05-07T23:52:26.897 回答