hashtable = {} hashtable["ABA"] = 13 hashtable["CAB"] = 12 hashtable["BAC"] = 15 puts hashtable i = hashtable.fetch("ABA") puts "ABAs age is #{i}" j = hashtable.fetch("BAC") puts "BACs age is #{j}"
Luckily, Ruby already provides Hash that represents HashTable.
As we can see we have stored the names ABA, CAB and BAC and their corresponding ages 13, 12 and 15 in the Hashtable.
hashtable["ABA"] = 13 hashtable["CAB"] = 12 hashtable["BAC"] = 15
But how they are stored in the HashTable will be decided by Ruby. As we are using the Hash provided by Ruby.
So, for ABA, a Hash Code is calculated by Ruby and the age of ABA is stored in some location decided by Ruby.
Similarly, the age of CAB and BAC is stored in the Hashtable after Ruby calculates the Hash Code, and decides where they will be stored.
After all the values are stored, we then check all the values stored in the Hashtable.
puts hashtable
Then we try to retrieve the age of ABA.
i = hashtable.fetch("ABA")
So, we pass the name of ABA and internally Ruby calculates the Hash Code for ABA and gives us the age of ABA from the Hashtable.
And we print the age of ABA on the screen.
puts "ABAs age is #{i}"
Similarly we retrieve the age of BAC and print it on the screen.
j = hashtable.fetch("BAC") puts "BACs age is #{j}"