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
Finding the minimum, maximum, sum and average are trivial and can be done easily in linear time as shown by sepp2k's answer above.
Finding the median is less trivial and the naive implementation (sorting, and then taking the middle element) runs in O(nlogn) time.
There are, however, algorithms that find the median in linear time (such as the median-of-5 algorithm). Others work even for any kind of order statistic (say, you want to find the 5th-smallest element). The problem with those is that you would have to implement them yourself, I know of no Ruby implementation.
O(nlogn) is quite fast already, so if you're not planning on working on huge datasets (and if you will need to sort your data anyway), you'll be fine with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With