Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try this:</p> <pre><code>arr = [5, 6, 7, 8] arr.inject{ |sum, el| sum + el }.to_f / arr.size =&gt; 6.5 </code></pre> <p>Note the <code>.to_f</code>, which you'll want for avoiding any problems from integer division. You can also do:</p> <pre><code>arr = [5, 6, 7, 8] arr.inject(0.0) { |sum, el| sum + el } / arr.size =&gt; 6.5 </code></pre> <p>You can define it as part of <code>Array</code> as another commenter has suggested, but you need to avoid integer division or your results will be wrong. Also, this isn't generally applicable to every possible element type (obviously, an average only makes sense for things that can be averaged). But if you want to go that route, use this:</p> <pre><code>class Array def sum inject(0.0) { |result, el| result + el } end def mean sum / size end end </code></pre> <p>If you haven't seen <code>inject</code> before, it's not as magical as it might appear. It iterates over each element and then applies an accumulator value to it. The accumulator is then handed to the next element. In this case, our accumulator is simply an integer that reflects the sum of all the previous elements.</p> <p><strong>Edit:</strong> Commenter Dave Ray proposed a nice improvement.</p> <p><strong>Edit:</strong> Commenter Glenn Jackman's proposal, using <code>arr.inject(:+).to_f</code>, is nice too but perhaps a bit too clever if you don't know what's going on. The <code>:+</code> is a symbol; when passed to inject, it applies the method named by the symbol (in this case, the addition operation) to each element against the accumulator value.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload