| Module | Indexable |
| In: |
lib/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.
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/core/facets/indexable.rb, line 217
217: def index(obj=nil, &block)
218: if block_given?
219: size.times do |i|
220: return i if yield(slice(i))
221: end
222: else
223: size.times do |i|
224: return i if obj == slice(i)
225: end
226: end
227: nil
228: 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/core/facets/indexable.rb, line 89
89: def mid(offset=0)
90: slice((size / 2) + offset)
91: end
Returns the middle element(s) of an array. Even-sized arrays, not having an exact middle, returns 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]
In contrast to mid which utilizes an offset.
# File lib/core/facets/indexable.rb, line 102
102: def middle
103: if size % 2 == 0
104: slice( (size / 2) - 1, 2 )
105: #[slice((size / 2) - 1, 1), slice(size / 2, 1)]
106: else
107: slice(size / 2)
108: end
109: 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..2
# File lib/core/facets/indexable.rb, line 242
242: def range(a=nil,z=nil)
243: if !a
244: 0..(size-1)
245: else
246: index(a)..index(z)
247: end
248: end