How would get find an average from an array?
If I have the array:
[0,4,8,2,5,0,2,6]
Averaging would give me 3.375.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try this:
Note the
.to_f, which you’ll want for avoiding any problems from integer division. You can also do:You can define it as part of
Arrayas 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:If you haven’t seen
injectbefore, 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.Edit: Commenter Dave Ray proposed a nice improvement.
Edit: Commenter Glenn Jackman’s proposal, using
arr.inject(:+).to_f, is nice too but perhaps a bit too clever if you don’t know what’s going on. The:+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.