Method: Indexable#middle
- Defined in:
- lib/core/facets/indexable.rb
#middle(birth = 0) ⇒ Object
Returns an Array of the middle element(s) of an array. Even-sized arrays, not having an exact middle, return a two-element array of the two middle elements.
[1,2,3,4,5].middle #=> [3]
[1,2,3,4,5,6].middle #=> [3,4]
A birth
can be give to widen the middle on either side.
[1,2,3,4,5].middle(1) #=> [2,3,4]
[1,2,3,4,5,6].middle(1) #=> [2,3,4,5]
In contrast to #mid which utilizes an offset.
97 98 99 100 101 102 103 104 |
# File 'lib/core/facets/indexable.rb', line 97 def middle(birth=0) i = size / 2 - birth if size % 2 == 0 slice(i - 1, 2 + (2 * birth)) else slice(i, 1 + (2 * birth)) end end |