DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Brontesewell
Brontesewell

Posted on

Hashes and Arrays in Ruby Programming

In this article we are going to examine Arrays and Hashes and their syntaxes, storing values, accessing and grabbing values and iterating over them.

Firstly what are Arrays and Hashes in Ruby?

Hashes and Arrays are indexed collections which store multiple objects(integer, string, floating number, etc) and values. They are accessed using a key. In Array’s the key is an integer and it is more efficient to access array elements than hashes. In Hashes the key is any object and hashes are more flexible than arrays.

Arrays [ ]

Lets take a look at an Array in Ruby

arr = [3, 4.55, β€œPoppy”, β€œThe Fat Cat”, 788, false, -54]

We can access each item in an array through its index number. The first item has an index of 0, the next has an index of 1, and it increases with each item starting left to right in the array. We always start counting at zero. For example:

puts arr[0] => 3                            [1st item]
puts arr[5] => false                        [6th item]
puts arr[3] => β€œThe Fat Cat”                [4th item]

Nested or Multi-dimensional Arrays

A Nested or Multi-dimensional Array is an array that has elements which are also arrays. We can do this because arrays can contain any kind of data. It is useful for storing groups of related data.

multi_arr = [ 
      [Hannah, β€œSoccer”, 12, β€œA average”], 
      [Tom, β€œIce Hockey”, 14, β€œC average”], 
      [Kate, β€œBasketball”, 15, β€œA average”]
  ]

We can access each item in the Multi-dimensional Array by doubling up on the bracket notation to navigate down to the second nested level of the array.

puts multi_arr[0][0] => Hannah                           [1st item][1st item in 1st item]
puts multi_arr[1] =>[Tom, β€œIce Hockey”, 14, β€œC average”]   [2nd item]
puts multi_arr[2][3] => β€œA average”                      [3rd item][4th item in 3rd item]

Hash { }

Lets take a look at a Hash in Ruby

hash = {
        β€œ3” => β€œthree”,
        β€œI Love Cats” => true,
        :nickname => β€œDan”,
        :numbers => [1, 2, β€œThree”]
}

In hashes we have key-value pairs where the key doesn’t have to be a number like in an array. To access a value in the hash you have to use the key in the brackets.

puts hash[β€œ3”] => three
puts hash[:nickname] => Dan
puts hash[:numbers][0] => 1    [within the numbers array get the 1st element (index 0)]

Iteration

Iteration is defined as the act or process of repeating. It is where a computer is instructed to preform a certain process over and over again for a specific number of times or until a specific condition has been met/reached.

For each iteration example in Arrays and Hashes below we will use the each method. Which iterates over each element in an array or hash.

Iterating over Array

arr = [3, 4.55, β€œPoppy”, β€œThe Fat Cat”, 788, false, -54]


arr.each do    | value |
     puts value
end

For every element in our array, 'each' runs the block and passes it the element as an argument(value in the example which is between the pipes | value | ).

πŸ‘‡ And it will print πŸ‘‡
3
4.55
Poppy
The Fat Cat
788
false
-54

Iterating over Nested Arrays

multi_arr = [ 
      [Hannah, β€œSoccer”, 12, β€œA average”], 
      [Tom, β€œIce Hockey”, 14, β€œC average”], 
      [Kate, β€œBasketball”, 15, β€œA average”]
  ]


multi_arr.each do |student_array|
  student_array.each do |student_detail|
            puts student_detail
   end
end

πŸ‘‡ And it will print πŸ‘‡
Hannah
Soccer
12
A average
Tom
Ice Hockey
14
C average
Kate
Basketball
15
A average

Iterating through the Hash

hash = {
        β€œ3” => β€œthree”,
        β€œI Love Cats” => true,
        :nickname => β€œDan”,
        :numbers => [1, 2, β€œThree”]
}


hash.each do    | key, value |
    puts β€œ#{key}: #{value}”
end

The only difference between iterating over a Hash vs array is that in a Hash the block has two arguments (key and value in the example which is between the pipes | key, value | ).

πŸ‘‡ And it will print πŸ‘‡
3: three
I Love Cats: true
nickname: Dan
numbers: 1, 2, β€œThree

In conclusion we learnt and explored syntaxes, storing values, accessing values and iterating over them. It really is not too hard when you break it down and make it simple! Hope this helped. Many more blogs coming!

Feel free to leave a comment with your thoughts or questions below!

From Bronte Sewell

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. 🌈