Module | Indexable |
In: |
lib/facets/core/facets/indexable.rb
|
Indexable is a mixin that provides index based methods, working soley with four methods: index, slice, splice and size.
These methods work in harmony. Where index returns a position of a given element, slice returns elements for given positions. splice is like slice but replaces the given position with new values. This mehtod is not part of ruby core, but it generally just an alias for #[]=, just as slice is an alias of #[]. size of course simply returns the total length of the indexable object.
NOTE: To test the folowing methods Indexable needs to be included into Array and array must have splice defined.
require 'facets/array/splice' class ::Array include Indexable end
CREDIT: Thomas Sawyer
Returns the index of the first element equal to the given object or satisfying the block condition.
[1,2,3,4].index{ |e| e == 3 } #=> 2 [1,2,3,4].index{ |e| e > 3 } #=> 3
# File lib/facets/core/facets/indexable.rb, line 237 def index(obj=nil, &block) if block_given? size.times do |i| return i if yield(slice(i)) end else size.times do |i| return i if obj == slice(i) end end nil end
Returns the middle element of an array, or the element offset from middle if the parameter is given. Even-sized arrays, not having an exact middle, return the middle-right element.
[1,2,3,4,5].mid #=> 3 [1,2,3,4,5,6].mid #=> 4 [1,2,3,4,5,6].mid(-1) #=> 3 [1,2,3,4,5,6].mid(-2) #=> 2 [1,2,3,4,5,6].mid(1) #=> 5
In other words, If there are an even number of elements the higher-indexed of the two center elements is indexed as orgin (0).
# File lib/facets/core/facets/indexable.rb, line 81 def mid(offset=0) slice((size / 2) + offset) end
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.
# File lib/facets/core/facets/indexable.rb, line 99 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
Returns the index range between two elements. If no elements are given, returns the range from first to last.
['a','b','c','d'].range #=> (0..3) ['a','b','c','d'].range('b','d') #=> (1..3)
# File lib/facets/core/facets/indexable.rb, line 261 def range(a=nil,z=-1) if a index(a)..index(z) else (0..(size-1)) end end
Fetch values from a start index thru an end index.
[1,2,3,4,5].thru(0,2) #=> [1,2,3] [1,2,3,4,5].thru(2,4) #=> [3,4,5] [1,2,3,4,5].thru(2) #=> [1,2,3] [1,2,3,4,5].thru(4) #=> [1,2,3,4,5]
# File lib/facets/core/facets/indexable.rb, line 116 def thru(from, to=nil) from, to = 0, from unless to to = size - 1 if to >= size a = [] i = from while i <= to a << slice(i) i += 1 end a end