3 # ISO does not define Hash#each_pair, so each_pair is defined in gem.
8 # Hash[ key, value, ... ] -> new_hash
9 # Hash[ [ [key, value], ... ] ] -> new_hash
10 # Hash[ object ] -> new_hash
12 # Creates a new hash populated with the given objects.
14 # Similar to the literal `{ _key_ => _value_, ... }`. In the first
15 # form, keys and values occur in pairs, so there must be an even number of
18 # The second and third form take a single argument which is either an array
19 # of key-value pairs or an object convertible to a hash.
21 # Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
22 # Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200}
23 # Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}
27 length = object.length
32 o.each { |k, v| h[k] = v }
34 elsif o.respond_to?(:to_a)
37 raise ArgumentError, "wrong element type #{i.class} (expected array)" unless i.respond_to?(:to_a)
46 raise ArgumentError, "invalid number of elements (#{i.size} for 1..2)"
53 unless length % 2 == 0
54 raise ArgumentError, 'odd number of arguments for Hash'
57 0.step(length - 2, 2) do |i|
58 h[object[i]] = object[i + 1]
65 # hsh.merge!(other_hash) -> hsh
66 # hsh.merge!(other_hash){|key, oldval, newval| block} -> hsh
68 # Adds the contents of _other_hash_ to _hsh_. If no block is specified,
69 # entries with duplicate keys are overwritten with the values from
70 # _other_hash_, otherwise the value of each duplicate key is determined by
71 # calling the block with the key, its value in _hsh_ and its value in
74 # h1 = { "a" => 100, "b" => 200 }
75 # h2 = { "b" => 254, "c" => 300 }
76 # h1.merge!(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
78 # h1 = { "a" => 100, "b" => 200 }
79 # h2 = { "b" => 254, "c" => 300 }
80 # h1.merge!(h2) { |key, v1, v2| v1 }
81 # #=> {"a"=>100, "b"=>200, "c"=>300}
84 def merge!(other, &block)
85 raise TypeError, "Hash required (#{other.class} given)" unless Hash === other
88 self[k] = (self.has_key?(k))? block.call(k, self[k], other[k]): other[k]
91 other.each_key{|k| self[k] = other[k]}
100 # hsh.compact! -> hsh
102 # Removes all nil values from the hash. Returns the hash.
103 # Returns nil if the hash does not contain nil values.
105 # h = { a: 1, b: false, c: nil }
106 # h.compact! #=> { a: 1, b: false }
114 return nil if (keys.size == nk.size)
125 # hsh.compact -> new_hsh
127 # Returns a new hash with the nil values/key pairs removed
129 # h = { a: 1, b: false, c: nil }
130 # h.compact #=> { a: 1, b: false }
131 # h #=> { a: 1, b: false, c: nil }
145 # hsh.fetch(key [, default] ) -> obj
146 # hsh.fetch(key) {| key | block } -> obj
148 # Returns a value from the hash for the given key. If the key can't be
149 # found, there are several options: With no other arguments, it will
150 # raise an <code>KeyError</code> exception; if <i>default</i> is
151 # given, then that will be returned; if the optional code block is
152 # specified, then that will be run and its result returned.
154 # h = { "a" => 100, "b" => 200 }
155 # h.fetch("a") #=> 100
156 # h.fetch("z", "go fish") #=> "go fish"
157 # h.fetch("z") { |el| "go fish, #{el}"} #=> "go fish, z"
159 # The following example shows that an exception is raised if the key
160 # is not found and a default value is not supplied.
162 # h = { "a" => 100, "b" => 200 }
167 # prog.rb:2:in 'fetch': key not found (KeyError)
171 def fetch(key, none=NONE, &block)
172 unless self.key?(key)
178 raise KeyError, "Key not found: #{key.inspect}"
187 # hsh.delete_if {| key, value | block } -> hsh
188 # hsh.delete_if -> an_enumerator
190 # Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
191 # evaluates to <code>true</code>.
193 # If no block is given, an enumerator is returned instead.
195 # h = { "a" => 100, "b" => 200, "c" => 300 }
196 # h.delete_if {|key, value| key >= "b" } #=> {"a"=>100}
199 def delete_if(&block)
200 return to_enum :delete_if unless block
203 self.delete(k) if block.call(k, v)
210 # hash.flatten -> an_array
211 # hash.flatten(level) -> an_array
213 # Returns a new array that is a one-dimensional flattening of this
214 # hash. That is, for every key or value that is an array, extract
215 # its elements into the new array. Unlike Array#flatten, this
216 # method does not flatten recursively by default. The optional
217 # <i>level</i> argument determines the level of recursion to flatten.
219 # a = {1=> "one", 2 => [2,"two"], 3 => "three"}
220 # a.flatten # => [1, "one", 2, [2, "two"], 3, "three"]
221 # a.flatten(2) # => [1, "one", 2, 2, "two", 3, "three"]
225 self.to_a.flatten(level)
230 # hsh.invert -> new_hash
232 # Returns a new hash created by using <i>hsh</i>'s values as keys, and
233 # the keys as values.
235 # h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
236 # h.invert #=> {0=>"a", 100=>"m", 200=>"d", 300=>"y"}
241 self.each {|k, v| h[v] = k }
247 # hsh.keep_if {| key, value | block } -> hsh
248 # hsh.keep_if -> an_enumerator
250 # Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
251 # evaluates to false.
253 # If no block is given, an enumerator is returned instead.
257 return to_enum :keep_if unless block
261 unless block.call([k, v])
270 # hsh.key(value) -> key
272 # Returns the key of an occurrence of a given value. If the value is
273 # not found, returns <code>nil</code>.
275 # h = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 }
290 # hsh.to_h -> hsh or new_hash
292 # Returns +self+. If called on a subclass of Hash, converts
293 # the receiver to a Hash object.
301 # hash < other -> true or false
303 # Returns <code>true</code> if <i>hash</i> is subset of
307 # h2 = {a:1, b:2, c:3}
313 raise TypeError, "can't convert #{hash.class} to Hash" unless Hash === hash
314 size < hash.size and all? {|key, val|
315 hash.key?(key) and hash[key] == val
321 # hash <= other -> true or false
323 # Returns <code>true</code> if <i>hash</i> is subset of
324 # <i>other</i> or equals to <i>other</i>.
327 # h2 = {a:1, b:2, c:3}
333 raise TypeError, "can't convert #{hash.class} to Hash" unless Hash === hash
334 size <= hash.size and all? {|key, val|
335 hash.key?(key) and hash[key] == val
341 # hash > other -> true or false
343 # Returns <code>true</code> if <i>other</i> is subset of
347 # h2 = {a:1, b:2, c:3}
353 raise TypeError, "can't convert #{hash.class} to Hash" unless Hash === hash
354 size > hash.size and hash.all? {|key, val|
355 key?(key) and self[key] == val
361 # hash >= other -> true or false
363 # Returns <code>true</code> if <i>other</i> is subset of
364 # <i>hash</i> or equals to <i>hash</i>.
367 # h2 = {a:1, b:2, c:3}
373 raise TypeError, "can't convert #{hash.class} to Hash" unless Hash === hash
374 size >= hash.size and hash.all? {|key, val|
375 key?(key) and self[key] == val
381 # hsh.dig(key,...) -> object
383 # Extracts the nested value specified by the sequence of <i>key</i>
384 # objects by calling +dig+ at each step, returning +nil+ if any
385 # intermediate step is +nil+.
398 # hsh.transform_keys {|key| block } -> new_hash
399 # hsh.transform_keys -> an_enumerator
401 # Returns a new hash, with the keys computed from running the block
402 # once for each key in the hash, and the values unchanged.
404 # If no block is given, an enumerator is returned instead.
406 def transform_keys(&block)
407 return to_enum :transform_keys unless block
409 self.keys.each do |k|
410 new_key = block.call(k)
411 hash[new_key] = self[k]
417 # hsh.transform_keys! {|key| block } -> hsh
418 # hsh.transform_keys! -> an_enumerator
420 # Invokes the given block once for each key in <i>hsh</i>, replacing it
421 # with the new key returned by the block, and then returns <i>hsh</i>.
423 # If no block is given, an enumerator is returned instead.
425 def transform_keys!(&block)
426 return to_enum :transform_keys! unless block
427 self.keys.each do |k|
430 k = block.call(k) if block
437 # hsh.transform_values {|value| block } -> new_hash
438 # hsh.transform_values -> an_enumerator
440 # Returns a new hash with the results of running the block once for
442 # This method does not change the keys.
444 # If no block is given, an enumerator is returned instead.
446 def transform_values(&b)
447 return to_enum :transform_values unless block_given?
449 self.keys.each do |k|
450 hash[k] = yield(self[k])
457 # hsh.transform_values! {|key| block } -> hsh
458 # hsh.transform_values! -> an_enumerator
460 # Invokes the given block once for each value in the hash, replacing
461 # with the new value returned by the block, and then returns <i>hsh</i>.
463 # If no block is given, an enumerator is returned instead.
465 def transform_values!(&b)
466 return to_enum :transform_values! unless block_given?
467 self.keys.each do |k|
468 self[k] = yield(self[k])
479 # hsh.fetch_values(key, ...) -> array
480 # hsh.fetch_values(key, ...) { |key| block } -> array
482 # Returns an array containing the values associated with the given keys
483 # but also raises <code>KeyError</code> when one of keys can't be found.
484 # Also see <code>Hash#values_at</code> and <code>Hash#fetch</code>.
486 # h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
488 # h.fetch_values("cow", "cat") #=> ["bovine", "feline"]
489 # h.fetch_values("cow", "bird") # raises KeyError
490 # h.fetch_values("cow", "bird") { |k| k.upcase } #=> ["bovine", "BIRD"]
492 def fetch_values(*keys, &block)
494 self.fetch(k, &block)