Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/midwire_common/array.rb

Overview

A light-weight super Array class

Instance Method Summary collapse

Instance Method Details

#binsearch(e, l = 0, u = length - 1) ⇒ Object

Binary search returns index if found or nil rubocop:disable Metrics/LineLength rubocop:disable Style/SpaceAfterComma, Style/SpaceAroundOperators, Style/SpaceAfterColon, Style/SpaceAfterSemicolon, Style/Semicolon



34
35
36
# File 'lib/midwire_common/array.rb', line 34

def binsearch(e, l = 0, u = length - 1)
  return if l>u;m=(l+u)/2;e<self[m]?u=m-1:l=m+1;e==self[m]?m:binsearch(e,l,u)
end

#count_occurrencesObject



3
4
5
6
7
# File 'lib/midwire_common/array.rb', line 3

def count_occurrences
  hash = Hash.new(0)
  each { |elem| hash[elem] += 1 }
  hash
end

#each_with_first_last(first_code, main_code, last_code) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/midwire_common/array.rb', line 21

def each_with_first_last(first_code, main_code, last_code)
  each_with_index do |item, ndx|
    case ndx
    when 0 then first_code.call(item)
    when size - 1 then last_code.call(item)
    else main_code.call(item)
    end
  end
end

#randomizeObject



9
10
11
# File 'lib/midwire_common/array.rb', line 9

def randomize
  sort_by { rand }
end

#randomize!Object



13
14
15
# File 'lib/midwire_common/array.rb', line 13

def randomize!
  replace(randomize)
end

#sort_case_insensitiveObject



17
18
19
# File 'lib/midwire_common/array.rb', line 17

def sort_case_insensitive
  sort_by(&:downcase)
end

#superjoin(*ldescr) ⇒ Object

Make a string from a multi-dimensional array : 1 dimension : [1,2,3].superjoin()

2 dimensions: (html table) [[1,2],].superjoin( %w</tr><tr> </tr></table>, %w</td><td> </td> )

> <table><tr><td>1</td><td>2</td></tr><tr><td>2</td><td>3</td></tr></table>



46
47
48
49
50
51
52
# File 'lib/midwire_common/array.rb', line 46

def superjoin(*ldescr)
  dim = ldescr[0]
  rest = ldescr[1..-1]
  dim[0] + map do |arr|
    (arr.respond_to?(:superjoin) && !rest.empty?) ? arr.superjoin(*rest) : arr.to_s
  end.join(dim[1]) + dim[2]
end