比方说,我在一家攀岩健身房工作,我正在努力简化出勤过程。在这里,我试图访问嵌套在哈希中的数组中的哈希中的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
答案 0 :(得分:0)
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
答案 1 :(得分:0)
当“ parties”不是哈希时,此代码将引发错误。您假设它是一个哈希,并为它编写了代码。因此,当未排除的内容到达时(如在您的测试输入中一样),它将最终引发异常:party_one是一个哈希,而party_two是一个字符串。我建议检查“派对”是否为哈希,然后继续执行该派对的代码。