I've written two simple calculations with Ruby which match the way that Microsoft Excel calculates the upper and lower quartiles for a given set of data - which is not the same as the generally accepted method (surprise).
My question is - how much and how best can these methods be refactored for maximum DRYness?
# Return an upper quartile value on the same basis as Microsoft Excel (Freund+Perles method) def excel_upper_quartile(array) return nil if array.empty? sorted_array = array.sort u = (0.25*(3*sorted_array.length+1)) if (u-u.truncate).is_a?(Integer) return sorted_array[(u-u.truncate)-1] else sample = sorted_array[u.truncate.abs-1] sample1 = sorted_array[(u.truncate.abs)] return sample+((sample1-sample)*(u-u.truncate)) end end # Return a lower quartile value on the same basis as Microsoft Excel (Freund+Perles method) def excel_lower_quartile(array) return nil if array.empty? sorted_array = array.sort u = (0.25*(sorted_array.length+3)) if (u-u.truncate).is_a?(Integer) return sorted_array[(u-u.truncate)-1] else sample = sorted_array[u.truncate.abs-1] sample1 = sorted_array[(u.truncate.abs)] return sample+((sample1-sample)*(u-u.truncate)) end end