English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Ruby Hashes (Hash)

Hash is a collection of key-value pairs like "key" => "value". Hash is similar to an array, but its index is not limited to using numbers.

The index of Hash (or called "key") can almost be any object.

Hash, although similar to arrays, has an important difference: the elements of Hash do not have a specific order. If order is important, you should use an array.

Creating a hash

Like arrays, there are various ways to create hashes. You can create a hash by new Class method to create an empty hash:

months = Hash.new

You can also use new Create a hash with a default value, a hash without a default value is nil:

months = Hash.new("month")
 
or
 
months = Hash.new "month"

When you access any key in a hash with a default value, if the key or value does not exist, accessing the hash will return the default value:

Online Example

#!/usr/bin/ruby
 
months = Hash.new("month")
 
puts "#{months[0]}"
puts "#{months[72"]"

The output result of the above example is:

month
month

Online Example

#!/usr/bin/ruby
 
H = Hash["a" => 100, "b" => 200]
 
puts "#{H['a']}"
puts "#{H['b']}"

The output result of the above example is:

100
200

You can use any Ruby object as a key or value, even an array, as shown in the following example:

[1,"jan"] => "January"

Built-in Hash Methods

If you need to call a Hash method, you must first instantiate a Hash object. Below are some ways to create a Hash object:

Hash[[key =>|, value]* ] or
 
Hash.new [or] Hash.new(obj) [or]
 
Hash.new { |hash, key| block }

This will return a new hash filled with the given object. Now, using the created object, we can call any available method. For example:

Online Example

#!/usr/bin/ruby
 
$, = ", "
months = Hash.new("month")
 
months = {"1" => "January", "2" => "February"
 
keys = months.keys
 
puts "#{keys}"

The output result of the above example is:

["1", "2"]

Below are the public hash methods (assuming hash Is a Hash object):

Serial NumberMethod & Description
1hash == other_hash
Check if two hashes have the same number of key-value pairs and if the pairs match each other to determine if the two hashes are equal.
2hash[key]
Use the key to reference the value from the hash. If the key is not found, return the default value.
3hash[key]=value
Convert value The given value with key Associate the given key.
4hash.clear
Remove all key-value pairs from the hash.
5hash.default(key = nil)
Returns hash The default value, if not set through default=, then returns nil. (If the key is hash is not present, then [] returns a default value.)
6hash.default = obj
For hash Set default values.
7hash.default_proc
If hash is returned if it is created by a block.
8hash.delete(key) [or]
array.delete(key) { |key| block }

Through key from hash to remove the key-value pair. If a block is used and no matching key-value pair is found, then return the result of the block. Compare it with delete_if to compare.
9hash.delete_if { |key,value| block }
block is true For each block in hash to remove the key-value pair.
10hash.each { |key,value| block }
Traversal hash, for each key Call the block once, passing the key-value as a two-element array.
11hash.each_key { |key| block }
Traversal hash, for each key Call the block once, passing key As a parameter.
12hash.each_key { |key_value_array| block }
Traversal hash, for each key Call the block once, passing key and value As a parameter.
13hash.each_value { |value| block }
Traversal hash, for each key Call the block once, passing value As a parameter.
14hash.empty?
Check if the hash is empty (does not contain key-value pairs), and return true or false.
15hash.fetch(key [, default] ) [or]
hash.fetch(key) { | key | block }

Through the given key from hash The return value. If the return value is not found keyis given and no other parameters are provided, then IndexError exception; if defaultThen it returns defaultIf an optional block is specified, then return the result of the block.
16hash.has_key?(key) [or] hash.include?(key) [or]
hash.key?(key) [or] hash.member?(key)

Check the given key Whether it exists in the hash, and returns true or false.
17hash.has_value?(value)
Check if the hash contains the given value.
18hash.index(value)
For the given value It returns keyIf no matching value is found, it returns nil.
19hash.indexes(keys)
return a new array consisting of the values of the given keys. Keys not found will insert the default value. This method is deprecated, please use select.
20hash.indices(keys)
return a new array consisting of the values of the given keys. Keys not found will insert the default value. This method is deprecated, please use select.
21hash.inspect
return the string representation of the hash.
22hash.invert
create a new hashis reversed hash of keys and values. That is, in the new hash,hash in the
23hash.keys
create a new array with hash keys in
24hash.length
return as an integer. hash size or length.
25hash.merge(other_hash) [or]
hash.merge(other_hash) { |key, oldval, newval| block }

Returns a new hash containing hash and other_hash content, rewriting the hash with other_hash key-value pairs with duplicate keys.
26hash.merge!(other_hash) [or]
hash.merge!(other_hash) { |key, oldval, newval| block }

is similar to merge, but the hash itself actually changes.
27hash.rehash
based on each key the current value to rebuild hash. If the value changes after insertion, this method will re-index hash.
28hash.reject { |key, value| block }
similar to delete_if, but operates on a copy of the hash. Equivalent to hsh.dup.delete_if.
29hash.reject! { |key, value| block }
equivalent to delete_if, but returns nil if no modification is made.
30hash.replace(other_hash)
Convert hash content is replaced with other_hash content.
31hash.select { |key, value| block }
return a new array consisting of block Returns true of hash comprising the key-value pairs from.
32hash.shift
from hash remove a key-value pair from the hash and return it as a two-element array.
33hash.size
return as an integer. hash of size or length.
34hash.sort
Convert hash converted into a two-dimensional array containing key-value pairs arrays, and then sorted.
35hash.store(key, value)
stored hash one of the key-value pairs.
36hash.to_a
Create a two-dimensional array from hash. Each key-value pair is converted to an array, and all these arrays are stored in an array.
37hash.to_hash
Returns hash(self).
38hash.to_s
Convert hash Converts it to an array and then converts that array to a string.
39hash.update(other_hash) [or]
hash.update(other_hash) {|key, oldval, newval| block}

Returns a new hash containing hash and other_hash content, rewrite hash with other_hash key-value pairs with duplicate keys.
40hash.value?(value)
Check hash Whether it contains the given value.
41hash.values
Returns a new array containing hash of all values.
42hash.values_at(obj, ...)
Returns a new array containing hash The value associated with the given key.