Finding the highest, lowest, total, average and median from an array in Ruby

user142019 picture user142019 · Jun 3, 2010 · Viewed 32.3k times · Source

I am creating a boxplot generator in Ruby, and I need to calculate some things.

Let's say I have this array:

arr = [1, 5, 7, 2, 53, 65, 24]

How can I find the lowest value (1), highest value (65), total (157), average (22.43) and median (7) from the above array?

Thanks

Answer

sepp2k picture sepp2k · Jun 3, 2010
lowest = arr.min
highest = arr.max
total = arr.inject(:+)
len = arr.length
average = total.to_f / len # to_f so we don't get an integer result
sorted = arr.sort
median = len % 2 == 1 ? sorted[len/2] : (sorted[len/2 - 1] + sorted[len/2]).to_f / 2