Class: Hash
Direct Known Subclasses
Class Method Summary collapse
-
.create(initial_hash = {}, &block) ⇒ Object
Create a hash given an ‘initial_hash`.
Instance Method Summary collapse
-
#rekey(key_map = nil, &block) ⇒ Object
Synonym for Hash#rekey, but modifies the receiver in place (and returns it).
-
#rekey!(key_map = nil, &block) ⇒ Object
Synonym for Hash#rekey, but modifies the receiver in place (and returns it).
-
#retrieve(key) ⇒ Object
Like #fetch but returns the results of calling ‘default_proc`, if defined, otherwise `default`.
-
#to_hash ⇒ Object
(also: #to_h)
Convert to Hash.
-
#to_stash ⇒ Object
Convert Hash to Stash.
Class Method Details
.create(initial_hash = {}, &block) ⇒ Object
Create a hash given an ‘initial_hash`.
11 12 13 14 15 |
# File 'lib/hashery/core_ext.rb', line 11 def self.create(initial_hash={}, &block) o = new &block o.update(initial_hash) o end |
Instance Method Details
#rekey(key_map = nil, &block) ⇒ Object
Synonym for Hash#rekey, but modifies the receiver in place (and returns it).
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/hashery/core_ext.rb', line 58 def rekey(key_map=nil, &block) if !(key_map or block) block = lambda{|k| k.to_sym} end key_map ||= {} hash = {} (keys - key_map.keys).each do |key| hash[key] = self[key] end key_map.each do |from, to| hash[to] = self[from] if key?(from) end hash2 = {} if block case block.arity when 0 raise ArgumentError, "arity of 0 for #{block.inspect}" when 2 hash.each do |k,v| nk = block.call(k,v) hash2[nk] = v end else hash.each do |k,v| nk = block[k] hash2[nk] = v end end else hash2 = hash end hash2 end |
#rekey!(key_map = nil, &block) ⇒ Object
Synonym for Hash#rekey, but modifies the receiver in place (and returns it).
114 115 116 |
# File 'lib/hashery/core_ext.rb', line 114 def rekey!(key_map=nil, &block) replace(rekey(key_map, &block)) end |
#retrieve(key) ⇒ Object
Like #fetch but returns the results of calling ‘default_proc`, if defined, otherwise `default`.
25 26 27 |
# File 'lib/hashery/core_ext.rb', line 25 def retrieve(key) fetch(key, default_proc ? default_proc[self, key] : default) end |
#to_hash ⇒ Object Also known as: to_h
Convert to Hash.
32 33 34 |
# File 'lib/hashery/core_ext.rb', line 32 def to_hash dup # -or- `h = {}; each{ |k,v| h[k] = v }; h` ? end |