Open In App

Ruby | Hash Class

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order. The default value of Hashes is nil. When a user tries to access the keys which do not exist in the hash, then the nil value is returned.
 

Class Method

1. [] : This method creates a new hash that is populated with the given objects. It is equivalent to creating a hash using literal {Key=>value….}. Keys and values are present in the pair so there is even number of arguments present.

Hash[(key=>value)*]

Example:

Ruby




# Ruby program to illustrate
# use of []
# Using []
p Hash["x", 30, "y", 19]
p Hash["x" => 30, "y" => 19]


Output:

{"x"=>30, "y"=>19}
{"x"=>30, "y"=>19}

2. new : This method returns a empty hash. If a hash is subsequently accessed by the key that does not match to the hash entry, the value returned by this method depends upon the style of new used to create a hash. In the first form the access return nil. If obj is specified then, this object is used for all default values. If a block is specified, then it will be called by the hash key and objects and return the default value. The values are stored in the hash (if necessary) depends upon the block. 

Hash.new
Hash.new(obj)
Hash.new{|hash, key|block}

Example:

Ruby




# Ruby program to illustrate
# use of new method
 
# Using new method
a = Hash.new("geeksforgeeks")
p a["x"] = 40
p a["y"] = 49
p a["x"]
p a["y"]
p a["z"]


Output: 

40
49
40
49
"geeksforgeeks"

3.try_convert : This method is used to convert obj into hash and returns hash or nil. It return nil when the obj does not convert into hash.

Hash.try_convert(obj)

Example:

Ruby




# Ruby program to illustrate
# use of try_convert method
 
# Using try_convert method
p Hash.try_convert({3=>8})
p Hash.try_convert("3=>8")


Output: 

{3=>8}
nil

Instance Method

Note: In the below-described methods, hsh variable is the instance of the Hash Class.

1. ==: It is known as Equality. It is used to check if two hashes are equal or not. If they are equal means they contain the same number of keys and the value related to these keys are equal, then it will return true otherwise returns false. 

hsh1 == hsh2

Example:

Ruby




# Ruby program to illustrate
# use of Equality
 
a1 = {"x" => 4, "y" => 109}
a2 = {"x" => 67, "f" => 78, "z" => 21}
a3 = {"f" => 78, "x" => 67, "z" => 21}
 
# Using equality
p a1 == a2
p a2 == a3


Output: 

false
true

2. [] : It is known as Element Reference. It retrieves the value that stored in the key. If it does not find any value then it return the default value.

hsh[key]

Example:

Ruby




# Ruby program to illustrate
# use of []
 
a = {"x" => 45, "y" => 67}
 
# Using []
p a["x"]
p a["z"]


Output: 

45
nil

3. []= : It is known as Element Assignment. It associates the value given by value with the key given by key.

hsh[key]=value

Example:

Ruby




# Ruby program to illustrate
# use of []=
 
a = {"x" => 45, "y" => 67}
 
# Using []=
a["x"]= 34
a["z"]= 89
p a


Output:

{"x"=>34, "y"=>67, "z"=>89}

4. clear : This method removes all the keys and their values from the hsh.

hsh.clear

Example:

Ruby




# Ruby program to illustrate
# use of clear method
 
a = {"x" => 45, "y" => 67}
 
# Using clear method
p a.clear


Output:

{}

5. default : This method return the default value. The value that returned by hsh[key], if key did not exist in hsh.

hsh.default(nil=key)

Example:

Ruby




# Ruby program to illustrate
# use of default method
 
a = Hash.new("geeksforgeeks")
 
# Using default method
p a.default
p a.default(2)


Output: 

"geeksforgeeks"
"geeksforgeeks"

6. default= : This method sets the default value (the value which is returned for a key and not exists in a hash). 

hsh.default=obj

7. default_proc : In this method if Hash.new was called with the block. Then it will return block otherwise return nil.

hsh.default_proc

Example:

Ruby




# Ruby program to illustrate
# use of default_proc method
 
a = Hash.new {|a, v| a[v] = v*v*v}
 
# Using default_proc method
b = a.default_proc
c = []
p b.call(c, 2)
p c 


Output: 

8
[nil, nil, 8]

8. delete :This method is used to delete the entry from hash whose key is key by returning the corresponding value. If the key is not found, then this method returns nil. If the optional block is given and the key is not found, then it will pass the block and return the result of the block.

hsh.delete(key)
hsh.delete(key){|key|block}

Example:

Ruby




# Ruby program to illustrate
# use of delete method
 
a = {"x" => 34, "y" => 60}
 
# Using delete method
p a.delete("x")
p a.delete("z")


Output: 

34
nil

9. delete_if : This method deletes the keys and their values from the hsh when the block is true.

hsh.delete_if{|key, value|block}

Example:

Ruby




# Ruby program to illustrate
# use of delete_if method
 
a = {"x" => 34, "y" => 60}
 
# Using delete_if method
p a.delete_if {|key, value| key >= "y"}


Output:

{"x"=>34}

10. each : This method calls block once for each key that present in hsh and pass key and value as a parameter. 

hsh.each{|key, value|block}

Example:

Ruby




# Ruby program to illustrate
# use of each method
 
a = {"x" => 34, "y" => 60}
 
# Using each method
a.each {|key, value| puts  "the value of #{key} is #{value}" }


Output: 

the value of x is 34
the value of y is 60

11. each_key : This method calls block once for each key that present in hsh and pass the key as a parameter.

hsh.each_key{|key|block}

Example:

Ruby




# Ruby program to illustrate
# use of each_key method
 
a = { "x" => 34, "y" => 60 }
 
# Using the each_key method
a.each_key {|key| puts key }


Output: 

x
y

12. each_pair : This method is similar to Hash#each method.

hsh.each_pair{|key, value|block}

13. each_value : This method calls block once for each key that present in hsh and pass value as a parameter.

hsh.each_key{|value|block}

Example:

Ruby




# Ruby program to illustrate
# use of each_value method
 
# Using each_value method
a = { "g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676 }
a.each_value{|value| puts value }


Output: 

23
25
3432
3453
676

14.empty?: This method return true if hsh does not contain any key and value pair. Otherwise, return false. 

hsh.empty?

15. fetch : This method return a value from the hsh using the given key. If the key is not found then it gives result depends on following conditions:

  • If no argument, then it will raise an exception.
  • If the default is given the it will return the default .
  • If an option block is present, then it will run the block and return the result of the block.

fetch method does not contain any default value. When the hash is created then it will only gaze for keys that present in the hash.

hsh.fetch(key[, default])
hsh.fetch(key){|key|block}

16. has_key? : This method return true if the given key is present in the hsh, otherwise, return false.

hsh.has_key?

Example:

Ruby




# Ruby program to illustrate
# use of has_key? method
 
a = {"g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676}
 
# Using has_key? method
p a.has_key?("x")
p a.has_key?("p")


Output: 

true
false

17. has_value? : This method return true if the given value is present for a key in the hsh, otherwise, return false.

hsh.has_value?

Example:

Ruby




# Ruby program to illustrate
# use of has_value? method
 
a = { "g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676 }
 
# Using has_value? method
p a.has_value?(23)
p a.has_value?(234)


Output: 

true
false

18. include? : This method is similar to Hash#has_key? method.

hsh.include?

19. index : This method return the key that contain the given value. If multiple key contains the given value, then it will return only a single key from all the keys and if not found then return nil. This is a Deprecated method. So we have to use Hash#key instead.

hsh.index(value)

20. invert : This method returns a new hash created by hsh‘s values as keys and the keys as values. If duplicate values are found, then it will contain only a single value is key from all the values. 

hsh.invert

Example: 

Ruby




# Ruby program to illustrate
# use of invert method
 
a = { "g" => 23, "h" => 25, "x"=>3432, "y"=>3453, "z"=>676 }
 
# Using invert method
p a.invert


Output: 

{23=>"g", 25=>"h", 3432=>"x", 3453=>"y", 676=>"z"}

21. key? : This method is similar to Hash#has_key?.

hsh.key?(key)

22. keys : This method returns an array of keys that present in the hash.

hsh.keys

23. length : This method returns the number of key and value pair from the hsh.

hsh.length

Example:

Ruby




# Ruby program to illustrate
# use of length method
 
a = {"g" => 23, "h" => 25}
 
# Using the length method
p a.length


Output: 

2

24. member? : This method is similar to Hash#has_key?.

hsh.member?(key)

25. merge : This method return new hash that contains the other_hsh content. If a block is specified, then each duplicate keys and their values is called from both the hashes and the value stored in the new hash.

hsh.merge(other_hsh)
hsh.merge(other_hsh){|key, old_value, new_value|block}

Example:

Ruby




# Ruby program to illustrate
# use of merge method
 
a1 = { "g" => 23, "h" => 25 }
a2 = { "h" => 2343, "i" => 4340 }
 
# Using merge method
p a1.merge(a2)


Output:

 {"g"=>23, "h"=>2343, "i"=>4340}

26. merge! : This method merges the content of one hsh into another hsh and overwrite entries with duplicate keys with those from other_hsh.

hsh.merge!(other_hsh)
hsh.merge!(other_hsh){|key, old_value, new_value|block}

Example:

Ruby




# Ruby program to illustrate
# use of merge! method
 
a1 = {"g" => 23, "h" => 25}
a2 = {"h" => 2343, "i" => 4340}
 
# Using merge! method
p a1.merge!(a2)
 
a1 = {"g" => 23, "h" => 25 }
 
# Using merge! method
p a1.merge!(a2) {|x, y, z| y}
p a1


Output: 

{"g"=>23, "h"=>2343, "i"=>4340}
{"g"=>23, "h"=>25, "i"=>4340}
{"g"=>23, "h"=>25, "i"=>4340}

27. rehash : This method recreate the hash based on the current hash value from each key. If the value of the keys hash changed, then it will re-index the hsh.

hsh.rehash

Example:

Ruby




# Ruby program to illustrate
# use of rehash method
 
x = [ "x", "g" ]
y = [ "y", "f" ]
a = { x => 45345, y => 6756 }
p a[x]
p x[0] = "h"
p a[x]
 
# Using rehash method
p a.rehash
p a[x]


Output: 

45345
"h"
nil
{["h", "g"]=>45345, ["y", "f"]=>6756}
45345

28. reject : This method is similar to Hash#delete_if, but it return the copy of hsh 

hsh.reject{|key, value|block}

29. reject! : This method is similar to Hash#delete_if, but return nil if no changes take place.

hsh.reject!{|key, value|block}

30. replace : This method replace the content of hsh from other_hsh.

hsh.replace(other_hsh)

Example:

Ruby




# Ruby program to illustrate
# use of replace method
 
a = { "x" => 34, "y" => 60, "z"=>33 }
 
# Using replace method
p a.replace({ "y" => 88, "x" => 987 })


Output: 

{"y"=>88, "x"=>987}

31. select : This method returns a new array that consists of a key and value pair only for which the given condition in the block is true.

hsh.select{|key, value| block}

Example:

Ruby




# Ruby program to illustrate
# use of select method
 
a = { "x" => 34, "y" => 60, "z"=>33 }
 
# Using select method
p a.select {|g, f| g > "x"}


Output: 

{"y"=>60, "z"=>33}

32. shift : This method remove the key and value pair from the hsh and return them as a two-item array. If the hshdoes not contain any pair then return nil.

hsh.shift

Example:

Ruby




# Ruby program to illustrate
# use of shift method
 
a = { "x" => 34, "y" => 60, "z"=>33 }
 
# Using the shift method
p a.shift
p a


Output:

["x", 34]
{"y"=>60, "z"=>33}

33. size : This method is similar to Hash#length.

hsh.size

34. sort : This method converts the hsh to the nested array of arrays that contains keys and their values and sort them by using Array#sort.

hsh.sort
hsh.sort{|a, b|block}

Example:

Ruby




# Ruby program to illustrate
# use of sort method
 
a = { "x" => 34, "y" => 60, "z"=>33 }
 
# Using sort method
p a.sort
p a.sort {|x, y| x[1]<=>y[1]}


Output: 

[["x", 34], ["y", 60], ["z", 33]]
[["z", 33], ["x", 34], ["y", 60]]

35. store : This method is similar to Hash#[]=.

hsh.store(key, value)

36. to_a : This method convert the hsh to the nested array of arrays that contains keys and their values.

hsh.to_a

Example:

Ruby




# Ruby program to illustrate
# use of to_a method
 
a = { "x" => 34, "y" => 60, "z"=>33 }
 
# Using to_a method
p a.to_a


Output: 

[["x", 34], ["y", 60], ["z", 33]]

37. to_s : This method convert hsh into a string. In other words, it converts the hash array, i.e. key and value pair in a string.

hsh.to_s

38. update : This method is similar to Hash#merge!.

hsh.update(other_hsh)
hsh.update(other_hsh){|key, old_value, new_value|block}

39. value? : This method is similar to Hash#has_value?.

hsh.value?(value)

40. values : This method returns an array which contains the values that present in hsh.

hsh.values

41. values_at : This method returns an array that contains the values of the specified keys and also provide default values for the keys that are not found.

hsh.values_at([keys])

Example:

Ruby




# Ruby program to illustrate
# use of values_at method
 
a = {"x" => 34, "y" => 60, "z"=>33}
 
# Using values_at method
p a.values_at("x", "y")
 
# Using default method
a.default = "geeks"
 
# Using values_at method
p a.values_at("x", "y", "z", "g")


Output: 

[34, 60]
[34, 60, 33, "geeks"]

Reference: https://docs.ruby-lang.org/en/2.0.0/Hash.html
 



Last Updated : 11 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads