Ruby Hash
A Hash is a collection of key-value pairs like "key" => "value". Hashes are similar to arrays, except that their indexes are not limited to numbers.
Hash indexes (or "keys") can be almost any object.
Although Hash is similar to an array, there is an important difference: Hash elements have no specific order. If order is important, you should use an array.
Creating Hashes
As with arrays, there are various ways to create a hash. You can create an empty hash via thenewclass method:
You can also usenewto create a hash with a default value. A hash without a default value isnil:
When you access any key in a hash with a default value, if the key or value does not exist, the hash will return the default value:
Example
Try it »
The output of the above example is:
month month
The output of the above example is:
100 200
You can use any Ruby object as a key or value, and even use an array, as shown in the following example:
Hash Built-in Methods
To call Hash methods, you need to instantiate a Hash object first. Here are the ways to create a Hash object instance:
This returns a new hash filled with the given object. Now, using the created object, we can call any available method. For example:
Example
Try it »
The output of the above example is:
["1", "2"]
The following are public hash methods (assuminghashhash is a Hash object):
| No. | Method & Description |
|---|---|
| 1 | hash == other_hash Checks whether two hashes have the same number of key-value pairs, and whether the key-value pairs match each other, to determine whether the two hashes are equal. |
| 2 | hash[key] Uses a key to reference a value from the hash. If the key is not found, returns the default value. |
| 3 | hash[key]=value holdvalueThe given value is associated with thekeygiven key. |
| 4 | hash.clear Removes all key-value pairs from the hash. |
| 5 | hash.default(key = nil) Returnshashthe default value of hash, or nil if not set via default=. (If the key is not present inhashhash, [] returns a default value.) |
| 6 | hash.default = obj ishashSets the default value. |
| 7 | hash.default_proc Ifhashhash was created with a block, returns the block. |
| 8 | hash.delete(key) [or] array.delete(key) { |key| block } Deleteskeyfromhashkey-value pairs from hash by key. If a block is used and no matching key-value pair is found, returns the result of the block. Compare it withdelete_ifdelete_if. |
| 9 | hash.delete_if { |key,value| block } For each block wheretrueevaluates to true, deletes key-value pairs fromhashhash. |
| 10 | hash.each { |key,value| block } Iterates overhashhash, for eachkeycalls block once, passing key-value as a two-element array. |
| 11 | hash.each_key { |key| block } Iterates overhashhash, for eachkeycalls block once, passingkeykey as an argument. |
| 12 | hash.each_key { |key_value_array| block } Iterates overhashhash, for eachkeycalls block once, passingkeyandvaluevalue as an argument. |
| 13 | hash.each_value { |value| block } Iterates overhashhash, for eachkeycalls block once, passingvaluekey-value as arguments. |
| 14 | hash.empty? Checks whether hash is empty (contains no key-value pairs), returnstrueorfalse。 |
| 15 | hash.fetch(key [, default] ) [or] hash.fetch(key) { | key | block } For the givenkeyfromhashkey, returns a value. If no key is foundkeyand no other arguments are given, raises anIndexErrorexception; ifdefaultdefault is given, returnsdefaultdefault; if an optional block is specified, returns the result of the block. |
| 16 | hash.has_key?(key) [or] hash.include?(key) [or] hash.key?(key) [or] hash.member?(key) Checks whether the givenkeykey exists in the hash, returnstrueorfalse。 |
| 17 | hash.has_value?(value) Checks whether the hash contains the givenvalue。 |
| 18 | hash.index(value) For the givenvaluevalue, returns the key in the hashkey, if no matching value is found, returns nil.nil。 |
| 19 | hash.indexes(keys) Returns a new array consisting of the values for the given keys. The default value will be inserted for keys not found. This method is deprecated; please use select. |
| 20 | hash.indices(keys) Returns a new array consisting of the values for the given keys. The default value will be inserted for keys not found. This method is deprecated; please use select. |
| 21 | hash.inspect Returns a printable string version of the hash. |
| 22 | hash.invert Creates a newhashhash, invertinghashthe keys/values inkeysandvalueshash. That is, in the new hash,hashthe keys in hash will become values, and values will become keys. |
| 23 | hash.keys Creates a new array containing the keys inhashhash. |
| 24 | hash.length Returns the size or length ofhashhash as an integer. |
| 25 | hash.merge(other_hash) [or] hash.merge(other_hash) { |key, oldval, newval| block } Returns a new hash containing the contents ofhashandother_hashhash, overwriting the key-value pairs in hash that have duplicate keys withother_hashother_hash. |
| 26 | hash.merge!(other_hash) [or] hash.merge!(other_hash) { |key, oldval, newval| block } Same as merge, but the hash actually changes. |
| 27 | hash.rehash Rebuilds hash based on eachkeykey's current value. If values change after insertion, this method re-indexeshashhash.hash。 |
| 28 | hash.reject { |key, value| block } Similar to delete_if, but works on a copy of the hash. Equivalent to hsh.dup.delete_if. |
| 29 | hash.reject! { |key, value| block } Equivalent to delete_if, but returns nil if no changes are made. |
| 30 | hash.replace(other_hash) holdhashReplaces the contents ofother_hashhash with the contents of |
| 31 | hash.select { |key, value| block } Returns a new array consisting ofblockthe key-value pairs intrueofhashhash. |
| 32 | hash.shift fromhashRemoves a key-value pair from hash and returns it as a two-element array. |
| 33 | hash.size Returns the size or length ofhashofsizehash as an integer. |
| 34 | hash.sort holdhashConverts to a two-dimensional array containing key-value pair arrays, then sorts it. |
| 35 | hash.store(key, value) Storeshasha key-value pair in hash. |
| 36 | hash.to_a Creates a two-dimensional array from hash. Each key-value pair is converted to an array, and all these arrays are stored in one array. |
| 37 | hash.to_hash Returnshash(self)。 |
| 38 | hash.to_s holdhashhash converted to an array, then that array converted to a string. |
| 39 | hash.update(other_hash) [or] hash.update(other_hash) {|key, oldval, newval| block} Returns a new hash containing the contents ofhashandother_hashhash, overwritinghashthe key-value pairs in hash that have duplicate keys withother_hashother_hash. |
| 40 | hash.value?(value) Checks whetherhashhash contains the givenvalue。 |
| 41 | hash.values Returns a new array containing all the values ofhashhash. |
| 42 | hash.values_at(obj, ...) Returns a new array containing the values inhashhash associated with the given keys. |