class Hashematics::Dictionary
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.
Attributes
default_value[R]
lookup[R]
Public Class Methods
new(default_value = nil)
click to toggle source
# File lib/hashematics/dictionary.rb, line 24 def initialize(default_value = nil) @default_value = default_value @lookup = {} freeze end
Public Instance Methods
add(enumerable) { |entry| ... }
click to toggle source
# 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
each() { |o| ... }
click to toggle source
# File lib/hashematics/dictionary.rb, line 56 def each return enum_for(:each) unless block_given? all.each { |o| yield o } end
exist?(key)
click to toggle source
# File lib/hashematics/dictionary.rb, line 52 def exist?(key) lookup.key?(key.to_s) end
get(key)
click to toggle source
# File lib/hashematics/dictionary.rb, line 48 def get(key) exist?(key) ? lookup[key.to_s] : default_value end
map(&block)
click to toggle source
# File lib/hashematics/dictionary.rb, line 62 def map(&block) return enum_for(:map) unless block_given? all.map(&block) end
set(key, object)
click to toggle source
# File lib/hashematics/dictionary.rb, line 42 def set(key, object) lookup[key.to_s] = object self end