RUBY Code to understand 'Hashes' & 'Symbol'

 

 Hashes are called associative arrays or dictionaries. In java we have ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet but in 'Ruby' we only have Hashes. 

 Normally we index arrays with integers but for Hash, we can index with anything!

"< key=>value >" this is the syntax for example, "Car_Name"=>"Lamborghini"

Here 'Car_Name' is the key/Index which is mapped to the Value 'Lamborghini'.

A Hash is created with comma separated keys and values inside curly braces.

Example 1:

Input:

Vehicle = {"Car_name" => "Lamborghini", "Car_age" => 2, "Car_Price" => 5000000 }

puts Vehicle["Car_age"]

Output:

2

 

Input:

Vehicle = {"Car_name" => "Lamborghini", "Car_age" => 2, "Car_Price" => 5000000 }

puts Vehicle["Car_Price"]

Output:

5000000


Here "Vehicle" is a Hash. 

Here we have declared the key as a string with in quotes. But in Ruby we can use a symbol.

Syntax of Symbol:

 "< :key>"

Example 2

Input:

V = {:Car_name => "Lamborghini", :Car_age => 2, :Car_Price => 5000000 }

puts V[:Car_age]

Output:

2

 A shorter way of writing the same code:

Example 3


Input:

V = {Car_name : "Lamborghini", Car_age : 2, Car_Price : 5000000 }

puts V[:Car_age]

Output:

2

Online Ruby compilers are available if you want to execute your own quote. https://www.onlinegdb.com/online_ruby_compiler

Comments