Ruby | Hashes Basics

Hash is a data structure that maintains a set of objects which are termed as the keys and each key associates a value with it. In simple words, a hash is a collection of unique keys and their values. Hashes are sometimes called as associative arrays because it associates values with each of the keys but there is a difference between hashes and arrays. Arrays always use an integer value for indexing whereas hashes use the object. Hashes are also known as the maps because they map keys to values.

Hash Literals or Creating Hashes: A hash is created using the hash literal which is a comma-separated list of key/value pairs and it always enclosed within curly braces {}. There are different ways to create a hash :

  • Using new class method: new class method will create an empty hash means there will be no default value for the created hash.

    Syntax:



    hash_variable = Hash.new

    Example:

    geeks = Hash.new

    This will create an empty hash geeks. You can also provide the default value to geeks in two ways as follows:

    geeks = Hash.new("GFG")
    
    or
    
    geeks = Hash.new "GFG"
    

    Here GFG is the default value. Whenever the key or value doesn’t exist in above hash then accessing the hash will return the default value “GFG”. To provide key/value pairs you have to modify the hash values which is discussed below in this article.

  • Using {} braces: In this hash variable is followed by = and curly braces {}. Between curly braces {}, the key/value pairs are created.

    Syntax:

    hash_variable = {"key1" => value1, "key2" => value2}
    


Fetching hash values: To fetch a hash value always put the required key within the square bracket [].

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate the creation
# of hashes and fetching the hash values
  
#!/usr/bin/ruby
  
# Creating a hash using new class method
# without the default value
geeks = Hash.new
  
# empty hash will return nothing on display
puts "#{geeks[4]}"
  
# creating hash using new class method
# providing default value
# this could be written as 
# geeks = Hash.new "GFG"
geeks_default = Hash.new("GFG")
  
# it will return GFG for every index of hash
puts "#{geeks_default[0]}"
puts "#{geeks_default[7]}"
  
# creating hash using {} braces
geeks_hash1 = {"DS" => 1, "Java" => 2}
  
  
# fetching values of hash using []
puts geeks_hash1['DS']   
puts geeks_hash1['Java']  

chevron_right


Output:


GFG
GFG
1
2


Modifying hashes in Ruby: Hash can be modified by adding or deleting a key value/pair in an already existing hash. Also, you can change the existing value of key in the hash.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate the modifying of hash
  
#!/usr/bin/ruby
  
# creating hash using {} braces
geeks_hash1 = {"DS" => 1, "Java" => 2}
  
puts "Before Modifying"
  
# fetching values of hash using []
puts geeks_hash1['DS']   
puts geeks_hash1['Java']  
  
puts "\n"
  
puts "After Modifying"
  
# modifying hash values
geeks_hash1["DS"] = 4
geeks_hash1["Java"] = 5
  
# fetching values of hash using []
puts geeks_hash1['DS'
puts geeks_hash1['Java'

chevron_right


Output:

Before Modifying
1
2

After Modifying
4
5

Note: Whenever user provides two different values to the same key in a hash then the previous value of the key is overwritten by the latest value of the key. Also, the program will run successfully but will give a warning as shown in below example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program to demonstrate the modifying hash
  
#!/usr/bin/ruby
  
# creating hash using {} braces
# providing two different values to key "DS"
geeks_hash1 = {"DS" => 1, "DS" => 4,"Java" => 2}
  
puts "Before Modifying"
  
# fetching values of hash using []
puts geeks_hash1['DS']   
puts geeks_hash1['Java']  
  
puts "\n"
  
puts "After Modifying"
  
# modifying hash values
geeks_hash1["DS"] = 4
geeks_hash1["Java"] = 5
  
# fetching values of hash using []
puts geeks_hash1['DS'
puts geeks_hash1['Java'

chevron_right


Output:

Before Modifying
4
2

After Modifying
4
5
main.rb:7: warning: key "DS" is duplicated and overwritten on line 7


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.