Class: Jinx::LazyHash

Inherits:
Hash show all
Defined in:
lib/jinx/helpers/lazy_hash.rb

Overview

A Hash that creates a new entry on demand.

Instance Method Summary collapse

Methods inherited from Hash

#base__merge!, #merge, #merge!

Methods included from Hasher

#==, #[], #assoc_values, #compact, #compose, #copy_recursive, #detect_hash_value, #detect_key, #detect_key_with_value, #detect_value, #difference, #each_key, #each_pair, #each_value, #enum_keys, #enum_keys_with_value, #enum_values, #filter, #filter_on_key, #filter_on_value, #flatten, #has_key?, #has_value?, #inspect, #join, #keys, #pretty_print, #pretty_print_cycle, #qp, #reject_keys, #reject_values, #select_keys, #select_values, #sort, #split, #to_hash, #to_s, #to_set, #transform_key, #transform_value, #union, #values

Methods included from Enumerable

#enumerate, #pp_s, #pretty_print, #pretty_print_cycle, #qp, #to_enum, #transitive_closure

Methods included from Collection

#compact, #compact_map, #detect_value, #detect_with_value, #difference, #empty?, #filter, #first, #flatten, #hashify, #intersect, #join, #last, #partial_sort, #partial_sort!, #partial_sort_by, #size, #to_compact_hash, #to_compact_hash_with_index, #to_series, #transform, #union

Constructor Details

#initialize(options = nil) ⇒ LazyHash

Creates a new Hash with the specified value factory proc. The factory proc has one argument, the key. If access by key fails, then a new association is created from the key to the result of calling the factory proc.

Example:

hash = LazyHash.new { |key| key.to_s }
hash[1] = "1"
hash[1] #=> "1"
hash[2] #=> "2"

If a block is not provided, then the default association value is nil, e.g.:

hash = LazyHash.new
hash.has_key?(1) #=> false
hash[1] #=> nil
hash.has_key?(1) #=> true

A nil key always returns nil. There is no hash entry for nil, e.g.:

hash = LazyHash.new { |key| key }
hash[nil] #=> nil
hash.has_key?(nil) #=> false

If the :compact option is set, then an entry is not created if the value initializer result is nil or empty, e.g.:

hash = LazyHash.new { |n| 10.div(n) unless n.zero? }
hash[0] #=> nil
hash.has_key?(0) #=> false


33
34
35
36
37
38
39
40
41
42
# File 'lib/jinx/helpers/lazy_hash.rb', line 33

def initialize(options=nil)
  reject_flag = Options.get(:compact, options)
  # Make the hash with the factory block
  super() do |hash, key|
    if key then
      value = yield key if block_given?
      hash[key] = value unless reject_flag and value.nil_or_empty?
    end
  end
end