Arrays in Ruby
Tags: ruby, beginners, codenewbie, tutorial
Published: 2020-11-18 14:59:05

# Welcome  

Welcome, dear readers, coders, and enthusiasts!
Here we are with our next article. To be honest, the more I write (blog), the more I learn, repeat, and get more professional. As you all know, “The best way to learn something is to teach it”. So I try to write more about what I learn and what I do. And it gives me an opportunity to revise what I have learned and nail it deeper in my mind.  
So, this time we are here to learn how to use and deal with Arrays in our beloved Ruby PL.

# Arrays
  
An array is a data structure that is present in almost all programming languages. In short, Array — is a collection of items that are placed in a certain order. You can store grades of students, product prices, product names and etc. in an Arrays. This is just an example. You can store more complex objects, data structures in an Array.  
In Ruby PL, compared to some other programming languages, we can store various typed data in an Array. I.e. you can store Numeric, String, Boolean, and some other kind of complex objects. In regular programming languages, you can only store one type of object, like only String or only Number. The main point is to treat them in the given order. All items in an Array have an index number.  
To summarize:  
* *Each of the elements in an array has an index number*
* *Indexing the elements starts with 0 (in an Array with ’n’ elements, the first element has index ‘0’, and the last element has an index number ‘n-1’)*
  
# Creating a new Array
  
To create a new Array it is enough to place it in square brackets. For instance:  
```
users = []  # Empty array

users = ["Arthur", "John", "Ford"] # 3 element Array

# If the Array consists of only 'String' data
users = %w(Arthur, John, Ford)
```
  
There is another way to create an Array. It is by using the ‘Array’ keyword.  
  
```
numbers = Array.new # Empty array

# Array with 3 nil elements
other_numbers = Array.new(3) # [nil, nil, nil]

# Array with defined elements
the_numbers = Array.new([15, 20, 25]) # [15, 20, 25]

# Another Array with defined numbers
five_tens = Array.new(5, 10) 
# [10, 10, 10, 10, 10]
```
  
As you can see, you can create empty Arrays and Arrays with predefined elements. If you want, you can create an Array with a defined number of elements that are all equal to a certain value, as shown in the last example.
  
# Accessing and updating elements
  
As we already have noted, all of the Array elements have an index number. What we always have to keep in mind is that the numbering starts with ‘0’.
  
* *in an array with ‘5’ elements, the first element has an index ‘0’, the last element has an index number ‘4’;*
* *in an array with ‘10’ elements, the first element has an index ‘0’, the last element has an index number ‘9’;*
* *in an array with ‘m’ elements, first element has an index ‘0’, the last element has an index number ‘m-1’;*
  
To access array elements we use square brackets. If we want to get the element with an index number 3 in an array named ‘grades’, we access its element using ‘grades[3]’.
  
```
seasons = ["Winter", "Sprint", "Summer", "Autumn"] # 4 elements

puts seasons[0] # The first element, with an indeks '0'
puts seasons[3] # The last element, with an index '3'

# Updating elements
seasons[0] = "Cold winter"
seasons[2] = "Hot summer"
```
  
Besides using index numbers, Ruby has made it easier and gave us built-in “first” and “last” methods. As you already have understood, these methods get you elements with indices ‘0’ and ‘n-1’.
  
```
cities = ["Boston", "Seoul", "Delhi", "Dubai"]

puts cities.first # "Boston"
puts cities.last # "Dubai"
```
  
# Inserting and removing elements
  
We have two groups of commands to use when we want to insert and remove elements from an Array. One group methods insert and remove from the end of an Array. The other group methods insert and remove elements from the start of an Array.
  
Here they are:
  
* *push (insert to the end of an Array)*
* *pop (remove from the end of an Array)*
* — — -
* *unshift (insert to the start of an Array)*
* *shift (remove from the start of an Array)*
  
```
planets = ["Mars", "Earth"]

# 'push' & 'pop' methods
planets.push "Neptune" # ["Mars", "Earth", "Neptune"]
planets.push "Saturn" # ["Mars", "Earth", "Neptune", "Saturn"]

# Remove last element (pop)
planets.pop # ["Mars", "Earth", "Neptune"]
planets.pop # ["Mars", "Earth"]

# 'unshift' & 'shift' methods
planets.unshift "Neptune" # ["Neptune", "Mars", "Earth"]
planets.unshift "Saturn" # ["Saturn", "Neptune", "Mars", "Earth"]
planets.shift # ["Neptune", "Mars", "Earth"]
planets.shift # ["Mars", "Earth"]

# delete_at
colors = ["yellow", "white", "blue", "black"]
colors.delete_at 2 
# Remove element with index '2', that is 'blue'
# ["yellow", "white, "black"]
```
Methods that insert new elements return a new state of the Array. Methods that remove an element from an Array, just return the removed element.
  
```
kids = ["Larry", "Brandon", "May", "John"]

first_kid = kids.shift
# first_kid => "Larry"
# kids = ["Brandon", "May", "John"]

last_kid = chagalar.pop
# last_kid=> "John"
# kids = ["Brandon", "May"]
```
  
An Array has another method to add elements to it. It is actually a short version of ‘push’ method. You can use it with “<<” symbols.
  
  
```
colors = ["yellow", "white"]

colors<<"blue"  # ["yellow", "white", "blue"]
colors<<"black"  # ["yellow", "white", "blue", "black"]
```
  
# Size of an Array
  
“Ruby” PL has three methods to get the number of elements in an Array. It returns the size of the Array. Many programming languages use either of these methods. But developers of Ruby decided to include them all together. Here the are:
  
* **length**
* **size**
* **count**
* **empty?** (checks whether the Array is empty or not, returns “true” or “false”)
  
```
colors = ["yellow", "white", "blue", "black"]
puts colors.length # 4
puts colors.size # 4
puts colors.count # 4
puts colors.empty? # false
```
  
# Iterating through Array elements
  
To iterate through Array elements we have two mostly used methods. They are “each” and “each_with_index” methods.
  
* **each** (iterates through Array elements)
* **each_with_index** (additionally, gives access to element index)
  
```
colors = ["yellow", "white", "blue", "black", "red"]

colors.each { |element| puts element } 
# yellow
# white
# blue
# black
# red

colors.each_with_index { |elem, index| puts "#{index} - #{elem}" } 
# 0 - yellow
# 1 - white
# 2 - blue
# 3 - black
# 4 - red
```
  
# Extra methods
  
* **sort** (Ordering): Used to order Array elements.
* **uniq** (non-repeating elements): returns only non-repeating, unique elements of the Array.
  
```
numbers = [1, 7, 2, 3, 3, 6, 5, 5]

puts numbers.sort 
# [1, 2, 3, 3, 5, 5, 6, 7]

numbers = numbers.uniq
# => [1, 2, 3, 5, 6, 7]
```
  
* **join**: joins Array elements into a single String.
* **split**: splits “String” type element into Array elements.
  
```
letters = %w(a b c d)

puts letters.join # "abcd"

puts "a b c".split 
# ["a", "b", "c"]
```
  
# Conclusion
  
Dear readers. Here we come to the end of the article about Ruby Arrays. Array methods are not only restricted to the ones listed here, in the article. We could have counted and written many more of them. No need to load the learner with loads at once. So if you want a bit more, just go to the documentation where you can find much more about Ruby and Arrays.
So, this is all for now. Stay hungry, stay healthy guys!