# Weighted Average Grade Calculation - hash iteration with nil

Jikku Jose
Apr 07, 2015
<p>What about converting all test scores to float?</p> <pre><code>&gt;&gt; jenny_grade_scores.inject({}) { |hash, array| hash[array[0]] = array[1].to_f; hash } =&gt; {"test_a"=&gt;0.95, "test_b"=&gt;0.85, "test_c"=&gt;0.0} </code></pre> <p>If you don't mind refactoring your code, consider the following:</p> <pre><code>WEIGHTS = { a: 0.25, b: 0.5, c: 0.25 } grades = { a: 0.95, b: 0.85 , c: nil } SUM_OF_WEIGHTS = WEIGHTS.inject(0) do |sum, (test, weight)| sum += grades[test].nil? ? 0 : weight end # =&gt; 0.75 weighted_score = grades.inject(0) do |w, (test, score)| w += (score.to_f * WEIGHTS[test]) end # =&gt; 0.6625 final_score = weighted_score / SUM_OF_WEIGHTS # =&gt; 0.8833333333333333 </code></pre> <p>Footnotes:</p> <ol> <li>Renaming the test keys to same key in all related hashes can simplify the problem.</li> <li><code>nil</code> when converted to float becomes 0.0.</li> <li><code>inject</code> &amp; <code>reduce</code> can do summation or similar collection related operation elegantly. More over its more idiomatic Ruby, try &amp; learn them if you are not familiar with it.</li> <li>Updated for non-penalized weight calculation.</li> </ol> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/27746163/Weighted%20Average%20Grade%20Calculation%20-%20hash%20iteration%20with%20nil/27746441">Stack Overflow</a>.</p>