当我尝试访问嵌套的哈希阵列时,我会收到(TypeError)



假设我在攀岩健身房工作,我正在尝试使出勤过程更容易。在这里,我试图访问嵌套在哈希中的数组中的哈希中的age值。尽管我收到了" Belayers"的适当输出号,但我也获得了parties[:attendance].each do |kid|行的TypeError。我知道这是错误的,但我不确定如何解决。任何建议都会有用。

def kids_hash
  kids_hash = {
    :party_one =>{
      :facilitator => 'Erica',
      :attendance => [
      {name: 'Harry', age: 6, wavers: 'yes', harness: "red", shoe_size: 3},
      {name: 'Frankie', age: 9, wavers: 'yes', harness: "blue", shoe_size: 7},
      {name: 'Gale', age: 4, wavers: 'yes', harness: "red", shoe_size: 3},
      {name: 'Rony', age: 4, wavers: 'no', harness: "red", shoe_size: 2},
      {name: 'Julia', age: 10, wavers: 'yes', harness: "blue", shoe_size: 9},
      {name: 'Sarah', age: 3, wavers: 'no', harness: "red", shoe_size: 13},
      {name: 'James', age: 3, wavers: 'yes', harness: "red", shoe_size: 2},
      {name: 'Kevin', age: 5, wavers: 'yes', harness: "red", shoe_size: 3},
      {name: 'Jessie', age: 11, wavers: 'yes', harness: "blue", shoe_size: 10}
      ]
    },
    :party_two => "not booked yet"
  }
end
def num_belayers
  kid_count = 0
  baby_count= 0
  kids_hash.values.each do |parties|
    parties[:attendance].each do |kid|
      if kid[:age] >= 5 
          kid_count += 1
        else
          baby_count +=1
        end
      end
    #if the kids are 5 y/o, we put 5 to a group
    belays_kids = kid_count / 5.00
    #if they are younger, there are 3 to a group
    belays_babies = baby_count / 3.00
    belays = belays_kids.ceil + belays_babies.ceil
    puts "You will need #{belays} belayers."
  end
end

party_two键未引用Hash,因此这就是为什么您会得到异常的原因。尝试以下代码。

def num_belayers
  kid_count = 0
  baby_count= 0
  kids_hash.each_value do |parties|
    next unless parties.is_a?(Hash)
    parties[:attendance].each do |kid|
      if kid[:age] >= 5 
          kid_count += 1
        else
          baby_count +=1
        end
      end
    #if the kids are 5 y/o, we put 5 to a group
    belays_kids = kid_count / 5.00
    #if they are younger, there are 3 to a group
    belays_babies = baby_count / 3.00
    belays = belays_kids.ceil + belays_babies.ceil
    puts "You will need #{belays} belayers."
  end
  nil 
end

此代码当" Partys"不是哈希时会引发错误。您假设它是哈希,并以相同的方式编写了代码。因此,当不外出的东西到达时,就像在party_one是一个hash一样,当party_two是字符串时,它最终会抛出异常。我建议检查"派对"是否是哈希,然后继续跳过该党的代码。

最新更新