I have an array of questions where each question has a category_id and a value.
I’d like to map these so that when the key (category_id) already exists in the hash, then the values are added together.
And, finally, I’d like to find the largest value in the hash:
h = Hash.new {|k, v| k[v] = 0}
@test_session.answered_questions.each do |q|
if h.key?(q.category_id)
#add q.value to the value stored in the hash
else
h = { q.category_id => q.value } #insert the "q.category_id" as key and with value "q.value"
end
end
key_with_max_value = h.max_by { |k, v| v }[0] #find the highest value
@result.category = key_with_max_value
@result.score = h[key_with_max_value].value
There is probably a lot better way to achieve this but I’m quite new to Ruby.
Each value in the hash will be initialized to zero with
Hash.new(0)and sinceh.max_byreturns the key value pair, you can directly assign them to your@resultvariable.