Introduction
Arrays and hashes are data structures that allow you to store multiple values at once. In this article, we will explore their syntaxes, how to populate them, retrieve values and loop through them. Let's go!
Arrays
Here is how an array is declared in Ruby:
arr = [1, 4, "Hello", false]
As you can see, an array can contain any type of data. The values are contained inside brackets [] and separated by commas.
Each item in a array has an numbered index. The first item has the index 0, the second the index 1, the third the second 2 ... You can access individual items in an array by using thoses indexes in a bracket notation:
puts arr[2] #Third item => "Hello"
puts arr[0] #First item => 1
Do not forget that we start counting from zero! This is the source of countless errors :D
Multi-dimensional arrays
Because arrays can contain any kind of data, they can also contain arrays. An array of ... arrays. We call them multi-dimensional arrays. The inner arrays work exactly the same way than any other arrays, and can contain any type of data.
multi_arr = [ [1, 4, "Hello"], [-54, false, "Ruby"] ]
Accessing values inside this data structure happens the same way than if you had one array, but you chain the bracket notations.
puts multi_arr[0][2] # [First item][Third item in first item] => "Hello"
puts multi_arr[1][0] # [Second item][First item in second item] => -54
Hashes
Hashes are another way to store multiple values inside a variable. In an array, you don't have any control over the indexes. They are numbers, and they go up by one with each item, starting from 0. In a hash, you provide key-value pairs, where the key doesn't have to be a number.
To create a new hash, you have two possiblities:
hash = Hash.new # will create an empty hash
# OR
populated_hash = {
"one" => "two",
42 => false,
true => "This is true",
[1, 2, "Hello"] => "Key is an array??"
}
If you are using the .new method, you must capitalize Hash.
As you can see, keys in a hash can be of any type of data. To add a new key-value pair to a hash, you can use the bracket notation as follows:
friend = "Joey"
hash["hello"] = "World"
hash[true] = "True"
hash[42] = "Answer Universe"
hash["Joey"] = friend
puts hash
# {"hello"=>"World", true=>"True", 42=>"Answer Universe", "Joey"=>"Joey"}
To access a value in a hash, use the key in brackets, like so:
puts hash["hello"] # World
puts hash[42] # Answer Universe
puts hash[true] # True
How to loop through arrays and hashes
You can loop through arrays and hashes by using the each method. The only difference between the two is that you can access both the key and the value when you are looping through a hash.
arr = [1, 4, "Hello", false]
hash = {
"hello" => "World",
true => "True",
42 => "Answer Universe",
"Joey" => "Joey"
}
arr.each { |value|
puts value
}
hash.each{ |key, value|
puts "Key = #{key} / Value = #{value}"
}
Notice that the current value in the data structure is put between pipes |value|. For the hash, you separate the key and the value by a comma. The code above will print out the following:
1
4
Hello
false
Key = hello / Value = World
Key = true / Value = True
Key = 42 / Value = Answer Universe
Key = Joey / Value = Joey
Nesting loops
Earlier, we saw something called multi-dimensional arrays, arrays nested inside an array. How would you procede to loop through this thing? Well, you would loop through the children arrays inside the parent array's loop. Like so:
multi_arr = [ [1, 4, "Hello"], [-54, false, "Ruby"] ]
multi_arr.each{ |child_arr|
child_arr.each{ |child_child_value|
puts child_child_value
}
}
And like that, we have all the values nested:
1
4
Hello
-54
false
Ruby
Conclusion
Now, you know what hashes and arrays are in Ruby. You also know how to retrieve values from them and loop through them. See you next time! Have fun!
Top comments (3)
Great article:
if you are covering arrays and "each" method, it might be worth a while to point out the "map" method. Since they are similiar and yet have very important differences:
Array#each executes the given block for each element of the array.
Array#map also executes the given block for each element of the array, but returns a new array whose values are the return values of each iteration of the block.
Use them effectively is very important. :)
Oh, I see! Thanks :)
I prefer colons to create key symbols at once