Hashes
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type.
Hash is a Class that ruby provides us to create Key-Value pairs.
_myData = Hash.new
_myData['name'] = "Bilal Haider"
_myData['age'] = 27
_myData['balance'] = 0
## using keys to access value
puts _myData['name']
puts _myData['age']
puts _myData['balance']
## using loop to print key value pairs
_myData.each do |h|
print h
end
There are many ways to create hashes :) lets explore some of them
first method you already saw in the example above,
here is second method to create hashes
_myData = {"name" => "Bilal Haider", "age" => 27, "balance" => 0}
## using keys to access values
puts _myData['name']
puts _myData['age']
puts _myData['balance']
## using loop to print key value pairs
_myData.each do |h|
print h
end
You can see that, we are getting same results ...
Here is another Way to write hashes, that is using symbols..
everytime you see ":something" that is called a symbol
_myData = {:name => "Bilal Haider", :age => 27, :balance => 0}
## using keys to access values
puts _myData[:name]
puts _myData[:age]
puts _myData[:balance]
## using loop to print key value pairs
_myData.each do |h|
print h
end
Here is another Way to write hashes, This syntax is similar to json :)
_myData = {name: "Bilal Haider", age: 27, balance: 0}
## using keys to access values
puts _myData[:name]
puts _myData[:age]
puts _myData[:balance]
## using loop to print key value pairs
_myData.each do |h|
print h
end
We have discussed 4 different ways of creating hashes, They are widely used when you are creating a web application,
we are going to create few example classes in upcoming articles, we will find out few scenarios where they can be used.
I hope you liked my article. don't forget to show thumbs up :)
If you want to learn more about Hashes
http://ruby-doc.org/core-2.2.0/Hash.html