Moving on. In order to build programs we need some building blocks (aka Data Structures). As I mentioned, Ruby is simple. There are only two data structures: arrays and hashes.
Ruby documentation says: “Arrays are ordered, integer-indexed collections of any object”. Sounds a little complicated. Let’s give arrays some love!
Photo by libertygrace0
Look at the picture a above. Here is the ordered collection of four blocks. If we count them from left to right, then we can refer to each block by it’s position or index. Let’s start counting from zero. The block number zero has the letter “L” on it. The block number one has the letter “O”. Number two is “V”. Number three is “E”. This is called zero indexed. We stick with blocks in this example, but it really can be any object.
Here is code representing the example above:
This is the most common way to define an array in Ruby. You start with an opening square bracket. Then, you define elements of the array separated by a comma sign. Finish it with a closing square bracket.
Now we have defined the array, let’s assign it to a variable so we can access it’s elements. Try it out in your IRB:
IRB executes code you type line by line. The text you typed in after » sign is code. The text that shows up after the => sign is a corresponding result.
You can refer to array’s element by it’s index (i.e. position). You start with specifying the variable my_array following with an opening square bracket sign. Then you specify a numeric index of an element you want to retrieve. It’s zero indexed, remember? Let’s say we want to get the letter O from my_array. It’s index is 1, so we access it like this:
Hashes are similar to arrays. Two main differences are:
- Instead of storing a single object, hashes store key value pairs.
- Instead of accessing an element by an index, you access it by a key.
Here is the simple hash that consist of one key value pair
The key is the string “name”. The value is the string “Alex Tamoykin”. A key and a value are separated by the equal sign followed by the greater than sight. Let’s call this => a rocket, just because it looks like it.
You start defining a hash with an opening curly brace following by key value pairs. Then you finish defining it with a closing curly brace.
Let’s try to access a value. The syntax is similar to array’s syntax but instead of using a numeric index, you need to use a key.
The last line of code we wrote returns the string “Alex Tamoykin”. You can specify as many key value pairs as you want. Just use a comma sign to separate it.
Photo by libertygrace0