Class: Hashery::KeyHash

Inherits:
CRUDHash show all
Defined in:
lib/hashery/key_hash.rb

Overview

The KeyHash class is a Hash class which accepts a block for normalizing keys.

The KeyHash class is essentially the same as a normal Hash. But notice the significant distinction of indifferent key access.

s = KeyHash.new
s[:x] = 1
s[:x]       #=> 1
s['x']      #=> 1

We can see that internally the key has indeed been converted to a String.

s.to_h      #=> {'x'=>1 }

By default all keys are converted to strings. This has two advantages over a regular Hash is many usecases. First it means hash entries have indifferent access. 1, "1" and :1 are all

Constant Summary

Constants inherited from CRUDHash

CRUDHash::NA

Instance Method Summary collapse

Methods inherited from CRUDHash

#<<, [], #[], #[]=, auto, #cast, #cast_key, #default_proc, #delete, #each, #fetch, #key?, #key_proc, #key_proc=, #merge, #read, #replace, #retrieve, #store, #to_hash, #update, #values_at

Methods inherited from Hash

create, #rekey, #rekey!, #retrieve, #to_hash, #to_stash

Constructor Details

#initialize(*default, &block) ⇒ KeyHash

Unlike a regular Hash, a KeyHash’s block sets the ‘key_proc` rather than the `default_proc`.



44
45
46
47
# File 'lib/hashery/key_hash.rb', line 44

def initialize(*default, &block)
  super(*default)
  @key_proc = block || Proc.new{ |k| k.to_s }
end