"value". Hashes are similar to arrays, but their indices are not limited to integers. The indices"> "value". Hashes are similar to arrays, but their indices are not limited to integers. The indices" />
Easy Tutorial
❮ Ruby Command Line Options Ruby Json ❯

Ruby Hash

A Hash is a collection of key-value pairs similar to "key" => "value". Hashes are similar to arrays, but their indices are not limited to integers.

The indices (or "keys") of a Hash can be almost any object.

Although Hashes are similar to arrays, there is a significant difference: the elements of a Hash have no 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 an empty Hash using the new class method:

months = Hash.new

You can also create a Hash with a default value using new, where a Hash without a default value returns 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:

Example

#!/usr/bin/ruby

months = Hash.new("month")

puts "#{months[0]}"
puts "#{months[72]}"

The output of the above example is:

month
month

Example

#!/usr/bin/ruby

H = Hash["a" => 100, "b" => 200]

puts "#{H['a']}"
puts "#{H['b']}"

The output 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"

Hash Built-in Methods

To call Hash methods, you need to instantiate a Hash object. Here are the ways to create Hash object instances:

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 objects. Now, using the created object, we can call any available methods. For example:

Example

#!/usr/bin/ruby

$, = ", "
months = Hash.new("month")

months = {"1" => "January", "2" => "February"}

keys = months.keys

puts "#{keys}"

The output of the above example is:

["1", "2"]

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

No. Method & Description
1 hash == other_hash<br>Checks if two hashes have the same number of key-value pairs and if the key-value pairs match each other to determine equality.
2 hash[key]<br>References the value from the hash using the key. Returns the default value if the key is not found.
3 hash[key]=value<br>Associates the given value with the given key.
4 hash.clear<br>Removes all key-value pairs from the hash.
5 hash.default(key = nil)<br>Returns the default value of the hash, or nil if not set via default=. (If the key does not exist in the hash, [] returns a default value.)
6 hash.default = obj<br>Sets the default value for the hash.
7 hash.default_proc<br>Returns the block if the hash was created by a block.
8 hash.delete(key) [or]<br>`array.delete(key) { key block }<br>Deletes the key-value pair from the hash by key. Returns the result of the block if the key is not found and a block is given. Compare withdelete_if`.
9 `hash.delete_if { key,value block }`<br>Deletes every key-value pair from the hash for which the block evaluates to true.
10 `hash.each { key,value block }`<br>Iterates over the hash, calling the block once for each key, passing the key-value pair as a two-element array.
11 `hash.each_key { key block }`<br>Iterates over the hash, calling the block once for each key, passing the key as a parameter.
12 `hash.each_key { key_value_array block }`<br>Iterates over the hash, calling the block once for each key, passing the key and value as parameters.
13 `hash.each_value { value block }`<br>Iterates over the hash, calling the block once for each key, passing the value as a parameter.
14 hash.empty?<br>Checks if the hash is empty (contains no key-value pairs), returning true or false.
15 hash.fetch(key [, default] ) [or]<br>`hash.fetch(key) { key block }<br>Returns the value from the hash for the given key. If the key is not found and no other arguments are provided, it raises anIndexError; ifdefaultis given, it returnsdefault`; if an optional block is specified, it returns the result of the block.
16 hash.has_key?(key) [or] hash.include?(key) [or]<br>hash.key?(key) [or] hash.member?(key)<br>Checks if the given key exists in the hash, returning true or false.
17 hash.has_value?(value)<br>Checks if the hash contains the given value.
18 hash.index(value)<br>Returns the key for the given value in the hash, or nil if no matching value is found.
19 hash.indexes(keys)<br>Returns a new array consisting of values for the given keys. Missing keys will insert the default value. This method is deprecated, use select instead.
20 hash.indices(keys)<br>Returns a new array consisting of values for the given keys. Missing keys will insert the default value. This method is deprecated, use select instead.
21 hash.inspect<br>Returns a printable string version of the hash.
22 hash.invert<br>Creates a new hash, inverting the keys and values of the hash. That is, keys in the hash become values in the new hash, and values become keys.
23 hash.keys<br>Creates a new array containing the keys from the hash.
24 hash.length<br>Returns the size or length of the hash as an integer.
25 hash.merge(other_hash) [or]<br>`hash.merge(other_hash) { key, oldval, newval block }<br>Returns a new hash containing the contents ofhashandother_hash, overwriting key-value pairs inhashwith duplicate keys fromother_hash`.
26 hash.merge!(other_hash) [or]<br>`hash.merge!(other_hash) { key, oldval, newval block }<br>Same asmerge, but actually changeshash`.
27 hash.rehash<br>Rebuilds the hash based on the current values for each key. If values have changed since they were inserted, this method re-indexes the hash.
28 `hash.reject { key, value block }<br>Similar todelete_if, but works on a copy of the hash. Equivalent tohsh.dup.delete_if`.
29 `hash.reject! { key, value block }<br>Equivalent todelete_if, but returnsnil` if no changes were made.
30 hash.replace(other_hash)<br>Replaces the contents of the hash with the contents of other_hash.
31 `hash.select { key, value block }<br>Returns a new array consisting of key-value pairs from the hash for which the block returnstrue`.
32 hash.shift<br>Removes a key-value pair from the hash and returns it as a two-element array.
33 hash.size<br>Returns the size or length of the hash as an integer.
34 hash.sort<br>Converts the hash to a two-dimensional array of [key, value] arrays and sorts it.
35 hash.store(key, value)<br>Stores a key-value pair in the hash.
36 hash.to_a<br>Creates a two-dimensional array from the hash. Each key-value pair is converted to an array, and all these arrays are stored in an array.
37 hash.to_hash<br>Returns the hash (self).
38 hash.to_s<br>Converts the hash to an array, then converts that array to a string.
39 hash.update(other_hash) [or]<br>`hash.update(other_hash) { key, oldval, newval block}<br>Returns a new hash containing the contents ofhashandother_hash, overwriting key-value pairs inhashwith duplicate keys fromother_hash`.
40 hash.value?(value)<br>Checks if the hash contains the given value.
41 hash.values<br>Returns a new array containing all the values of the hash.
42 hash.values_at(obj, ...)<br>Returns a new array containing the values associated with the given keys in the hash.
❮ Ruby Command Line Options Ruby Json ❯