- Read Tutorial
- Watch Guide Video
We're finally getting to work with collections in Ruby! We're going to start with the Array data type. In Ruby arrays are a common data structure that can be utilized in Ruby programs to store a collection of data types, including: integers, floats, strings, and even other arrays. We have used arrays quite a bit already in this course. So, in this lesson I want to take a step back and walk through some foundational concepts surrounding arrays.
There are two traditional ways to create an array of elements. The first one is:
x = [12, 3, 454, 234, 234]
Though this is the most common way to create an array, there is also another way to do it which is to use the Array.new
syntax, like so:
y = Array.new y[0] = 543
This will create an array, store it in the y
variable and then add the value of 543
as the 0th
element in the collection.
devCamp Note: Arrays have a different numbering system, they start counting from 0
instead of 1
.
Now suppose that I want to add a value to the tenth element in the array, then I can do add this code:
y[10] = 432
If I print y
, my output will be:
As you can see, our 0th
element is 543
and tenth element is 432
, but the remaining values are nil
, this is because we haven't filled them. So, you need to keep in mind that an array will fill empty spots if you don't provide the values for them.
To iterate over an array that we create, we can use the each
iterator method:
y.each do |i| puts i end
The output will be:
So now you have a good understanding of how to create an array data structure, how to add values to the array, and how to iterate through the collection.