我怎样才能在这个哈希数组中迭代接收一个特定的值:RUBY。

问题描述 投票:0回答:2

我的哈希值如下。

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 hashmap iteration each arrayiterator
2个回答
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]]

0
投票
>aoh.collect { |i| i[:ingredients].collect { |g| puts g[:ingredient] } }
   Gin
   Vodka
   Lillet Blonde
   White rum
   Lime juice
   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"]} 
© www.soinside.com 2019 - 2024. All rights reserved.