Ruby v1.6 Class and Library Reference: Hash

class Hash |
Parent: | Object
Version: | 1.6

### Index:

[ ] new == [ ] [ ]= clear default default= delete delete_if each each_key each_pair each_value empty? fetch has_key? has_value? include? index indexes indices invert key? keys length member? rehash reject reject! replace shift size sort store to_a to_s update value? values

A `Hash` is a collection of key-value pairs. It is similar to an `Array`, except that indexing is done via arbitrary keys of any object type, not an integer index. The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order.

Hashes have a default value that is returned when accessing keys that do not exist in the hash. By default, that value is `nil`.

mixins
Enumerable: | collect, detect, each_with_index, entries, find, find_all, grep, include?, map, max, member?, min, reject, select, sort, to_a

class methods
[ ] | Hash[ [key => value]* ] -> aHash
|  | Creates a new hash populated with the given objects. Equivalent to the literal `{ key, value, ... }`. Keys and values occur in pairs, so there must be an even number of arguments.
`Hash["a", 100, "b", 200]` | -> | `{"a"=>100, "b"=>200}`
`Hash["a" => 100, "b" => 200]` | -> | `{"a"=>100, "b"=>200}`
`{ "a" => 100, "b" => 200 }` | -> | `{"a"=>100, "b"=>200}`
new | Hash.new( anObject=`nil` ) -> aHash
|  | Returns a new, empty hash. If anObject is specified, it will be used as the default value.
`h = Hash.new("Go Fish")`
`h["a"] = 100`
`h["b"] = 200`
`h["a"]` | -> | `100`
`h["c"]` | -> | `"Go Fish"`

instance methods
== | hsh == anOtherHash -> `true` or `false`
|  | Equality-Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to `Object#==`) the corresponding elements in the other hash.
`h1 = { "a" => 1, "c" => 2 }`
`h2 = { "a" => 1, "c" => 2, 7 => 35 }`
`h3 = { "a" => 1, "c" => 2, 7 => 35 }`
`h4 = { "a" => 1, "d" => 2, "f" => 35 }`
`h1 == h2` | -> | `false`
`h2 == h3` | -> | `true`
`h3 == h4` | -> | `false`
[ ] | hsh[ aKeyObject ] -> aValueObject
|  | Element Reference-Retrieves the aValueObject stored for aKeyObject. If not found, returns the default value.
`h = { "a" => 100, "b" => 200 }`
`h["a"]` | -> | `100`
`h["c"]` | -> | `nil`
[ ]= | hsh[ aKeyObject ] = aValueObject -> aValueObject
|  | Element Assignment-Associates the value given by aValueObject with the key given by aKeyObject. aKeyObject should not have its value changed while it is in use as a key (a `String` passed as a key will be duplicated and frozen).
`h = { "a" => 100, "b" => 200 }`
`h["a"] = 9`
`h["c"] = 4`
`h` | -> | `{"a"=>9, "b"=>200, "c"=>4}`
clear | hsh.clear -> hsh
|  | Removes all key-value pairs from hsh.
`h = { "a" => 100, "b" => 200 }` | -> | `{"a"=>100, "b"=>200}`
`h.clear` | -> | `{}`
default | hsh.default -> anObject
|  | Returns the ``default value''-that is, the value returned for a key that does not exist in the hash. Defaults to `nil`. See also `Hash#default=`.
default= | hsh.default = anObject -> hsh
|  | Sets the ``default value''-that is, the value returned for a key that does not exist in the hash. Defaults to `nil`.
`h = { "a" => 100, "b" => 200 }`
`h.default = "Go fish"`
`h["a"]` | -> | `100`
`h["z"]` | -> | `"Go fish"`
delete | hsh.delete( aKeyObject ) -> aValueObject hsh.delete( aKeyObject ) {| aKeyObject | block } -> aValueObject
|  | Deletes and returns a key-value pair from hsh whose key is equal to aKeyObject. If the key is not found, returns the default value. If the optional code block is given and the key is not found, pass in the key and return the result of block.
`h = { "a" => 100, "b" => 200 }`
`h.delete("a")` | -> | `100`
`h.delete("z")` | -> | `nil`
`h.delete("z") { |el| "#{el} not found" }` | -> | `"z not found"`
delete_if | hsh.delete_if {| key, value | block } -> hsh
|  | Deletes every key-value pair from hsh for which block evaluates to `true`.
`h = { "a" => 100, "b" => 200, "c" => 300 }`
`h.delete_if {|key, value| key >= "b" }` | -> | `{"a"=>100}`
each | hsh.each {| key, value | block } -> hsh
|  | Calls block once for each key in hsh, passing the key and value as parameters.
    h = { "a" => 100, "b" => 200 }
    h.each {|key, value| print key, " is ", value, "\n" }
produces:
    a is 100
    b is 200
each_key | hsh.each_key {| key | block } -> hsh
|  | Calls block once for each key in hsh, passing the key as a parameter.
    h = { "a" => 100, "b" => 200 }
    h.each_key {|key| puts key }
produces:
    a
    b
each_pair | hsh.each_pair {| key, value | block } -> hsh
|  | Synonym for `Hash#each`.
each_value | hsh.each_value {| value | block } -> hsh
|  | Calls block once for each key in hsh, passing the value as a parameter.
    h = { "a" => 100, "b" => 200 }
    h.each_value {|value| puts value }
produces:
    100
    200
empty? | hsh.empty? -> `true` or `false`
|  | Returns `true` if hsh contains no key-value pairs.
`{}.empty?` | -> | `true`
fetch | hsh.fetch( aKeyObject [, aDefObject] ) -> anObject hsh.fetch( aKeyObject ) {| aKeyObject | block } -> anObject
|  | Returns a value from the hash for the given key. If the key can't be found, there are several options: With no other arguments, it will raise an `IndexError` exception; if aDefObject is given, then that will be returned; if the optional code block is specified, then that will be run and its result returned.
`h = { "a" => 100, "b" => 200 }`
`h.fetch("a")` | -> | `100`
`h.fetch("z", "go fish")` | -> | `"go fish"`
`h.fetch("z") { |el| "go fish, #{el}"}` | -> | `"go fish, z"`
The following example shows that an exception is raised if the key is not found and a default value is not supplied.
    h = { "a" => 100, "b" => 200 }
    h.fetch("z")
produces:
    prog.rb:2:in `fetch': key not found (IndexError)
    	from prog.rb:2
has_key? | hsh.has_key?( aKeyObject ) -> `true` or `false`
|  | Returns `true` if the given key is present in hsh.
`h = { "a" => 100, "b" => 200 }`
`h.has_key?("a")` | -> | `true`
`h.has_key?("z")` | -> | `false`
has_value? | hsh.has_value?( aValueObject ) -> `true` or `false`
|  | Returns `true` if the given value is present for some key in hsh.
`h = { "a" => 100, "b" => 200 }`
`h.has_value?(100)` | -> | `true`
`h.has_value?(999)` | -> | `false`
include? | hsh.include?( aKeyObject ) -> `true` or `false`
|  | Synonym for `Hash#has_key?`.
index | hsh.index( aValueObject ) -> aKeyObject
|  | Returns the key for a given value. If not found, returns the default value.
`h = { "a" => 100, "b" => 200 }`
`h.index(200)` | -> | `"b"`
`h.index(999)` | -> | `nil`
indexes | hsh.indexes( [key]+ ) -> anArray
|  | Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found.
`h = { "a" => 100, "b" => 200, "c" => 300 }`
`h.indexes("a", "c")` | -> | `[100, 300]`
`h.indexes("a", "c", "z")` | -> | `[100, 300, nil]`
indices | hsh.indices( [key]+ ) -> anArray
|  | Synonym for `Hash#indexes`.
invert | hsh.invert -> aHash
|  | Returns a new hash created by using hsh's values as keys, and the keys as values.
`h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }`
`h.invert` | -> | `{200=>"d", 300=>"y", 0=>"a", 100=>"n"}`
key? | hsh.key?( aKeyObject ) -> `true` or `false`
|  | Synonym for `Hash#has_key?`.
keys | hsh.keys -> anArray
|  | Returns a new array populated with the keys from this hash. See also `Hash#values`.
`h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }`
`h.keys` | -> | `["a", "b", "c", "d"]`
length | hsh.length -> aFixnum
|  | Returns the number of key-value pairs in the hash.
`h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }`
`h.length` | -> | `4`
`h.delete("a")` | -> | `200`
`h.length` | -> | `3`
member? | hsh.member?( aKeyObject ) -> `true` or `false`
|  | Synonym for `Hash#has_key?`.
rehash | hsh.rehash -> hsh
|  | Rebuilds the hash based on the current hash values for each key. If values of key objects have changed since they were inserted, this method will reindex hsh. If `Hash#rehash` is called while an iterator is traversing the hash, an `IndexError` will be raised in the iterator.
`a = [ "a", "b" ]`
`c = [ "c", "d" ]`
`h = { a => 100, c => 300 }`
`h[a]` | -> | `100`
`a[0] = "z"`
`h[a]` | -> | `nil`
`h.rehash` | -> | `{["c", "d"]=>300, ["z", "b"]=>100}`
`h[a]` | -> | `100`
reject | hsh.reject {| key, value | block } -> aHash
|  | Same as `Hash#delete_if`, but works on (and returns) a copy of the hsh. Equivalent to `hsh.dup.delete_if`.
reject! | hsh.reject! {| key, value | block } -> hsh or `nil`
|  | Equivalent to `Hash#delete_if`, but returns `nil` if no changes were made.
replace | hsh.replace( anOtherHash ) -> hsh
|  | Replaces the contents of hsh with the contents of anOtherHash.
`h = { "a" => 100, "b" => 200 }`
`h.replace({ "c" => 300, "d" => 400 })` | -> | `{"c"=>300, "d"=>400}`
shift | hsh.shift -> anArray or `nil`
|  | Removes a key-value pair from hsh and returns it as the two-item array `[` key, value `]`, or `nil` if the hash is empty.
`h = { 1 => "a", 2 => "b", 3 => "c" }`
`h.shift` | -> | `[1, "a"]`
`h` | -> | `{2=>"b", 3=>"c"}`
size | hsh.size -> aFixnum
|  | Synonym for `Hash#length`.
sort | hsh.sort -> anArray hsh.sort {| a, b | block } -> anArray
|  | Converts hsh to a nested array of `[` key, value `]` arrays and sorts it, using `Array#sort`.
`h = { "a" => 20, "b" => 30, "c" => 10 }`
`h.sort` | -> | `[["a", 20], ["b", 30], ["c", 10]]`
`h.sort {|a,b| a[1]<=>b[1]}` | -> | `[["c", 10], ["a", 20], ["b", 30]]`
store | hsh.store( aKeyObject, aValueObject ) -> aValueObject
|  | Synonym for Element Assignment (`Hash#[]=`).
to_a | hsh.to_a -> anArray
|  | Converts hsh to a nested array of `[` key, value `]` arrays.
`h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }`
`h.to_a` | -> | `[["a", 100], ["c", 300], ["d", 400]]`
to_s | hsh.to_s -> aString
|  | Converts hsh to a string by converting the hash to an array of `[` key, value `]` pairs and then converting that array to a string using `Array#join` with the default separator.
`h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }`
`h.to_s` | -> | `"a100c300d400"`
update | hsh.update( anOtherHash ) -> hsh
|  | Adds the contents of anOtherHash to hsh, overwriting entries with duplicate keys with those from anOtherHash.
`h1 = { "a" => 100, "b" => 200 }`
`h2 = { "b" => 254, "c" => 300 }`
`h1.update(h2)` | -> | `{"a"=>100, "b"=>254, "c"=>300}`
value? | hsh.value?( aValueObject ) -> `true` or `false`
|  | Synonym for `Hash#has_value?`.
values | hsh.values -> anArray
|  | Returns a new array populated with the values from hsh. See also `Hash#keys`.
`h = { "a" => 100, "b" => 200, "c" => 300 }`
`h.values` | -> | `[100, 200, 300]`

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2000 Addison Wesley Longman, Inc. Released under the terms of the Open Publication License V1.0.
This reference is available for download.