Class: Hashery::KeyHash
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 equivalent --any object that defines #to_s can be used as a key. Secondly, since strings are garbage collected so will default KeyHash objects.
But keys can be normalized by any function. Theses functions can be quite unique.
h = KeyHash.new(0){ |k| k.to_i }
h[1.34] += 1
h[1.20] += 1
h[1.00] += 1
h #=> { 1 => 3 }
Class Method Summary (collapse)
Instance Method Summary (collapse)
-
- (KeyHash) initialize(*default, &block)
constructor
Unlike a regular Hash, a KeyHash's block sets the `key_proc` rather than the `default_proc`.
Methods inherited from CRUDHash
#<<, #[], #[]=, #delete, #each, #fetch, #key?, #key_proc, #key_proc=, #merge, #replace, #store, #to_hash, #update, #values_at
Methods inherited from Hash
Methods included from CoreExt
#rekey, #rekey!, #to_h, #to_hash
Constructor Details
- (KeyHash) initialize(*default, &block)
Unlike a regular Hash, a KeyHash's block sets the `key_proc` rather than the `default_proc`.
51 52 53 54 |
# File 'lib/hashery/key_hash.rb', line 51 def initialize(*default, &block) super(*default) @key_proc = block || Proc.new{ |k| k.to_s } end |
Class Method Details
+ (Object) [](*hash)
41 42 43 44 45 |
# File 'lib/hashery/key_hash.rb', line 41 def self.[](*hash) s = new super(*hash).each{ |k,v| s[k] = v } s end |