Method: Array#median
- Defined in:
- lib/core/facets/array/median.rb
#median(offset = 0) ⇒ Object
Determines the sorted middle element.
a = %w{a a b b c c c}
a.median #=> "b"
When there are an even number of elements, the greater of the two middle elements is given.
a = %w{a a b b c c c d}
a.median #=> "c"
An offset can be supplied to get an element relative to the middle.
a = %w{a a b b c c c d}
a.median(-1) #=> "b"
The the array is empty, nil
is returned.
23 24 25 26 27 28 29 30 |
# File 'lib/core/facets/array/median.rb', line 23 def median(offset=0) return nil if self.size == 0 tmp = self.sort mid = (tmp.size / 2).to_i + offset tmp[mid] end |