我有这样的数组数据:
work_list = {
"data": {
"1": {
"team": "Design",
"members": nil,
"workload": {
"process": {
"total": 50,
"finish": 36,
"un_finish": 14,
}
}
},
"2": {
"team": "Account",
"members": 15,
"workload": {
"process": {
"total": 30,
"finish": 20,
"un_finish": 10,
}
}
}
}
}
我想通过以下方式计算两个团队的总工作量:
list = work_list["data"]
count = 0
list.each do |num|
num.each do |details|
work = num["workload"]["process"]["total"]
count += work
end
end
puts "The total amount of works: #{count}"
这里的错误是:"nil:NilClass (NoMethodError(的未定义方法'each'
代码的问题在于你使用:
来构建哈希:
"workload": {
"process": {
"total": 50,
"finish": 36,
"un_finish": 14,
}
}
这是 Ruby 中的有效语法,但此哈希的键将是符号,而不是预期的字符串,因此您需要通过符号访问此哈希的数据:
data_hash = work_list[:"data"]
count = 0
data_hash.each do |index, data|
work = data[:"workload"][:"process"][:"total"]
count += work
end
puts "The total amount of works: #{count}"
如果要使用字符串,则需要按如下方式构造哈希:
"workload" => {
"process" => {
"total" => 50,
"finish" => 36,
"un_finish" => 14,
}
}
您是在哈希而不是数组上进行迭代
list.each do |num, info|
work = info["workload"]["process"]["total"]
count += work
end