Class: Array
Instance Method Summary collapse
-
#binary_insert(item) ⇒ Object
performs a binary insert on the array (assumes the array is already sorted).
- #index_for_first_non_blank_value ⇒ Object
- #indices_for_value(value) ⇒ Object
- #map_with_index(&block) ⇒ Object
- #map_with_index! ⇒ Object
- #to_h ⇒ Object
Instance Method Details
#binary_insert(item) ⇒ Object
performs a binary insert on the array (assumes the array is already sorted)
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/extensions/array.rb', line 17 def binary_insert item if item > last push item else left_bound = 0 right_bound = size - 1 while left_bound < right_bound middle_index = left_bound + (right_bound - left_bound) / 2 if item < self[middle_index] right_bound = middle_index elsif item > self[middle_index] left_bound = middle_index+1 else break end end middle_index = left_bound if left_bound == right_bound insert middle_index, item end end |
#index_for_first_non_blank_value ⇒ Object
46 47 48 49 |
# File 'lib/extensions/array.rb', line 46 def index_for_first_non_blank_value each_with_index { |v, i| return i if v.present? } nil end |
#indices_for_value(value) ⇒ Object
38 39 40 41 42 43 44 |
# File 'lib/extensions/array.rb', line 38 def indices_for_value value indices = [] each_with_index do |v, i| indices.push i if v == value end indices end |
#map_with_index(&block) ⇒ Object
12 13 14 |
# File 'lib/extensions/array.rb', line 12 def map_with_index(& block) dup.map_with_index!(& block) end |
#map_with_index! ⇒ Object
6 7 8 9 10 |
# File 'lib/extensions/array.rb', line 6 def map_with_index! each_with_index do |e, idx| self[idx] = yield(e, idx); end end |
#to_h ⇒ Object
2 3 4 |
# File 'lib/extensions/array.rb', line 2 def to_h inject({}) { |h, v| h[v] = 1; h } end |