1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
class Hash
#
# Create a hash given an `initial_hash`.
#
# initial_hash - Hash or hash-like object to use as priming data.
# block - Procedure used by initialize (e.g. default_proc).
#
# Returns a `Hash`.
#
def self.create(initial_hash={}, &block)
o = new &block
o.update(initial_hash)
o
end
#
# Like #fetch but returns the results of calling `default_proc`, if defined,
# otherwise `default`.
#
# key - Hash key to lookup.
#
# Returns value of Hash entry or `nil`.
#
def retrieve(key)
fetch(key, default_proc ? default_proc[self, key] : default)
end
#
# Convert to Hash.
#
def to_hash
dup # -or- `h = {}; each{ |k,v| h[k] = v }; h` ?
end \
unless method_defined?(:to_hash)
#
# For a Hash, `#to_h` is the same as `#to_hash`.
#
alias :to_h :to_hash \
unless method_defined?(:to_h)
#
# Synonym for Hash#rekey, but modifies the receiver in place (and returns it).
#
# key_map - Hash of old key to new key.
# block - Procedure to convert keys, which can take just the key
# or both key and value as arguments.
#
# Examples
#
# foo = { :name=>'Gavin', :wife=>:Lisa }
# foo.rekey!{ |k| k.to_s } #=> { "name"=>"Gavin", "wife"=>:Lisa }
# foo.inspect #=> { "name"=>"Gavin", "wife"=>:Lisa }
#
# Returns `Hash`.
#
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
#
# Synonym for Hash#rekey, but modifies the receiver in place (and returns it).
#
# key_map - Hash of old key to new key.
# block - Procedure to convert keys, which can take just the key
# or both key and value as arguments.
#
# Examples
#
# foo = { :name=>'Gavin', :wife=>:Lisa }
# foo.rekey!{ |k| k.to_s } #=> { "name"=>"Gavin", "wife"=>:Lisa }
# foo #=> { "name"=>"Gavin", "wife"=>:Lisa }
#
# Returns `Hash`.
#
def rekey!(key_map=nil, &block)
replace(rekey(key_map, &block))
end
end
|