Ruby Programming Tutorial - Lesson 28 - Hashes in Ruby

By @bilal-haider3/19/2018ruby

main-qimg-fbc470474c857cb32a07817132429914.png

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

Screenshot from 2018-03-20 01-50-50.png

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

Screenshot from 2018-03-20 01-55-46.png

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

Screenshot from 2018-03-20 02-00-08.png

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

Screenshot from 2018-03-20 02-02-32.png

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

29

comments