How do I create an average from a Ruby array?
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.Thanks!
Fernando G.
answered 03/17/20
Ruby and JavaScript Web Developer
What you can do is:
- you sum all the number inside of the array using .sum
- then you change the total from being an integer to a float number using .to_f
- then you divide that by the total number of elements inside the array using .size
- then you change that number from an integer to a float using the .to_f
It looks like like this:
arr = [0,4,8,2,5,0,2,6]
arr.sum.to_f/arr.size.to_f
Still looking for help? Get the right answer, fast.
OR
Find an Online Tutor Now
Choose an expert and meet online.
No packages or subscriptions, pay only for the time you need.