views:

70

answers:

1

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

+5  A: 
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 = (sorted[len/2] + sorted[(len+1)/2]) / 2
sepp2k
You need to be a bit more careful with the median, in case `arr.length` is divisible by 2. A method that should always work is `do sortedarr = arr.sort ; medpt1 = arr.length / 2 ; medpt2 = (arr.length+1)/2 ; (sortedarr[medpt1] + sortedarr[medpt2]).to_f / 2 ; end`, but obviously that's more expensive, and not as nice and pretty, as what you have in your answer.
Aidan Cully
@Aidan: Thanks. Fixed it.
sepp2k
One minor note: arr.inject(:+) will only work in Ruby 1.8.7 or greater (or if another library has implemented Symbol#to_proc, as Rails' ActiveSupport does). Otherwise, arr.inject {|sum, n| sum + n} would work.
Greg Campbell
@GregCampbell: `arr.inject(:+)` does not invoke `Symbol#to_proc`, inject invokes `rb_funcall` directly when given a symbol (which is a lot faster than passing a block (or worse using Symbol#to_proc)). But you're right that it only works in 1.8.7+.
sepp2k