Ruby Fundamentals: Arrays

Ruby Fundamentals: Arrays

In Ruby, to access elements, bracket notation is used with the index of the element.

fruits = ["banana", "mango", "pineapple"] 
fruits[0]
# => "banana"
fruits[1]
# => "mango"

Bracket notation can be used to update the elements as well. For example;

fruits [2] = "orange"
# => "orange"
fruits
# => ["banana", "mango", "orange"]

Ruby also has easier ways of accessing elements at the beginning and end of the array which are:

fruits.first 
# => "banana"
fruits.last 
# => "orange"

Just as in JavaScript, slice can be used to return selected elements of an array, Ruby uses range notation to achieve the same. For example;

fruits[0..1]
# => ["banana", "mango"]
fruits[0...2]
# => ["banana", "mango"]

With range notation, the two dots mean “all numbers up to and including the last one” and the three dots mean “all numbers up to but not including the last one”.

Concat method:

num1 = [1, 2, 3]
num2 = [4, 5, 6]
num1.concat(num2)
# => [1, 2, 3, 4, 5, 6]
num1 
# => [1, 2, 3, 4, 5, 6]

method:

num1 = [1, 2, 3]
num2 = [4, 5, 6]
num1 + num2
# => [1, 2, 3, 4, 5, 6]
num1
# => [1, 2, 3]

Removing Elements from Arrays

Ruby uses the pop and shift method to remove elements from the end or the beginning of an array.

fruits = ["banana", "mango", "pineapple"]
# => ["banana", "mango", "pineapple"]
fruits.pop
# => "pineapple"
fruits
# => ["banana", "mango"]
fruits.shift
# => "banana"
fruits
# => ["mango"]

Advanced Array Methods The include method is used to check if a particular element is in the array:

letters = ["x", "y", "z"]
letters.include?("y")
# => true
letters.include?("e")
# => false
Ruby also has a sum method which will add every element in the array: 
[1, 3, 5].sum
# => 9

There is the reverse method that will return an array in a reverse order: letters.reverse.

# => ["x", "y", "z"]
letters
# => ["z", "y", "x"]

Lastly, ruby also has the uniq method that will return unique elements from an array:

breakfast = ["bread", "bread", "coffee", "eggs"]
# => ["bread", "bread", "coffee", "eggs"]
breakfast.uniq
# => ["bread", "coffee", "eggs"]

Special Array Syntax

Ruby uses %w method to create an array of strings assuming each string is one word:

%w[how are you]
# => ["how", "are", "you"]

Ruby uses %i method to create an array of symbols:

%i[how are you]
# => [:how, :are, :you]

Happy coding