Class: Brain::Lookup

Inherits:
Object
  • Object
show all
Defined in:
lib/brain/lookup.rb

Class Method Summary collapse

Class Method Details

.build_lookup(hashes) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/brain/lookup.rb', line 4

def build_lookup(hashes)
  # [{a: 1}, {b: 6, c: 7}] -> {a: 0, b: 1, c: 2}
  h = hashes.reduce do |memo, hash|
    memo.merge hash
  end
  lookup_from_hash h
end

.lookup_from_array(array) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/brain/lookup.rb', line 41

def lookup_from_array(array)
  lookup = {}
  z = 0
  array.reverse.each do |i|
    lookup[i] = z
    z += 1
  end
end

.lookup_from_hash(hash) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/brain/lookup.rb', line 12

def lookup_from_hash(hash)
  # {a: 6, b: 7} -> {a: 0, b: 1}
  lookup = {}
  index = 0
  hash.each do |k, v|
    lookup[k] = index
    index += 1
  end
  lookup
end

.to_array(lookup, hash) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/brain/lookup.rb', line 23

def to_array(lookup, hash)
  # {a: 0, b: 1}, {a: 6} -> [6, 0]
  array = []
  lookup.each do |k, v|
    array[lookup[k]] = hash[k] || 0
  end
  array
end

.to_hash(lookup, array) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/brain/lookup.rb', line 32

def to_hash(lookup, array)
  # {a: 0, b: 1}, [6, 7] -> {a: 6, b: 7}
  hash = {}
  lookup.each do |k, v|
    hash[k] = array[lookup[k]]
  end
  hash
end