Class: Hashematics::Dictionary

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/hashematics/dictionary.rb

Overview

A Dictionary is an array with a constant O(1) lookup time. It is basically a cross of a hash and an array. We could easily use a hashes everywhere, but explicitly coding our intentions of this common intra-library hash use is a nice way to communicate intentions while minimizing duplication.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default_value = nil) ⇒ Dictionary

Returns a new instance of Dictionary.



24
25
26
27
28
29
# File 'lib/hashematics/dictionary.rb', line 24

def initialize(default_value = nil)
  @default_value = default_value
  @lookup = {}

  freeze
end

Instance Attribute Details

#default_valueObject (readonly)

Returns the value of attribute default_value.



18
19
20
# File 'lib/hashematics/dictionary.rb', line 18

def default_value
  @default_value
end

Instance Method Details

#add(enumerable) ⇒ Object

Raises:

  • (ArgumentError)


31
32
33
34
35
36
37
38
39
40
# File 'lib/hashematics/dictionary.rb', line 31

def add(enumerable)
  raise ArgumentError, 'block must be given for key resolution' unless block_given?

  enumerable.each do |entry|
    key = yield entry
    set(key, entry)
  end

  self
end

#eachObject



56
57
58
59
60
# File 'lib/hashematics/dictionary.rb', line 56

def each
  return enum_for(:each) unless block_given?

  all.each { |o| yield o }
end

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/hashematics/dictionary.rb', line 52

def exist?(key)
  lookup.key?(key.to_s)
end

#get(key) ⇒ Object



48
49
50
# File 'lib/hashematics/dictionary.rb', line 48

def get(key)
  exist?(key) ? lookup[key.to_s] : default_value
end

#map(&block) ⇒ Object



62
63
64
65
66
# File 'lib/hashematics/dictionary.rb', line 62

def map(&block)
  return enum_for(:map) unless block_given?

  all.map(&block)
end

#set(key, object) ⇒ Object



42
43
44
45
46
# File 'lib/hashematics/dictionary.rb', line 42

def set(key, object)
  lookup[key.to_s] = object

  self
end