Почему я получаю NoMethodError, повторяющуюся в Hash Embedded в массиве в Ruby?
Я продолжаю получать следующее сообщение об ошибке для моего кода. (Попытка перебрать хеш, встроенный в массив, чтобы вернуть наибольшее значение и связанный с ним ключ). Ошибка появляется после первого цикла.
Traceback (последний вызов был последним): 6: из main.rb:53: в
<main>' 5: from main.rb:53:in
карта ' 4: от main.rb:53: вeach' 3: from main.rb:53:in
раз ' 2: от main.rb:58: вblock in <main>' 1: from main.rb:58:in
каждый 'main.rb: 60: inblock (2 levels) in <main>': undefined method
[] 'для nil:NilClass (NoMethodError)
#assigns number of participants in array
num_participants = 2
#embedded hash within array (of participants)
participants = [{"participant_name"=> "Liz Lee", "cupcakes_sold" => 41, "cupcakes_left" => 31, "cakes_sold" => 12, "cakes_left" => 2},
{"participant_name" => "John Jay", "cupcakes_sold" => 44, "cupcakes_left" => 2, "cakes_sold" => 22, "cakes_left" => 4}]
#calculates total amount raised by each hash in participants array
#and populates new hash key 'proceeds' for each hash in participants array
#then loops through to update most_raised amount and assign highest_earner
counter = 0
most_raised = 0
highest_earner = ""
num_participants.times.map do
profits = 2 * participants[0 + counter]['cookies_sold'] -
participants[0 + counter]['cookies_left'] -
participants[0 + counter]['cookies_sold'] +
6 * participants[0 + counter]['cakes_sold'] -
3 * participants[0 + counter]['cakes_sold'] -
3 * participants[0 + counter]['cakes_left']
participants[0 + counter]['proceeds'] = profits.to_i
puts "\nProceeds raised by #{participants[0+counter]['participant_name'].capitalize}:
$#{participants[0+counter]['proceeds']}" +"."
counter+=1
['participant_name', 'proceeds'].each do
if (max < profits)
most_raised = participants[0+counter]['proceeds'].to_i
highest_earner = participants[0+counter]['participant_name']
end
end
end
puts "#{highest_earner.capitalize} raised the most:$#{most_raised}"
2 ответа
Решение: я разделил свои петли.
#calculates total amount raised by each participant
counter = 0
participants.each do
profits = 2 * participants[0 + counter]['cookies_sold'] -
participants[0 + counter]['cookies_left'] - participants[0 + counter]['cookies_sold'] + 6 * participants[0 + counter]['cakes_sold'] -
3 * participants[0 + counter]['cakes_sold'] - 3 *
participants[0 + counter]['cakes_left']
participants[0 + counter]['proceeds'] = profits.to_i
puts "\n\e[36mProceeds raised by #{participants[0+counter]['participant_name'].capitalize}:\e[0m $#{participants[0+counter]['proceeds']}" +"."
counter+=1
end
#calculates highest earner and highest amount raised
counter = 0
most_raised = 0
highest_earner = ""
participants.each do
if (most_raised < participants[0+counter]['proceeds'])
most_raised = participants[0+counter]['proceeds'].to_i
highest_earner = participants[0+counter]['participant_name']
counter+=1
end
end
puts most_raised
puts highest_earner
Так как вы установили counter=0, вы никогда не получите первый хеш при выполнении участниками [0 + counter] (который всегда равен участникам [0])
Я пропустил ваш счетчик +=1 Извините, этот ответ не имеет значения.