May 19, 2017
Ruby Array No Comments

Ruby Array an Introduction

Ruby array are ordered, integer indexed collection of objects. It means we can take objects and keep them in order and keep their position in same order and we can refer to those objects by their positions. We can refer to those objects with the integer index whenever required. Ruby array are no special than arrays in other programming languages like C/C++ or Java. They work the same way as in other programming languages.

One way to think about Ruby array is the long last seat in public bus. It can hold about seven different people. We can refer to those people with the position of seat they belong. Ruby array are required because for example we need ten different variables v1,v2,v3…v10 of some data type in our program. Then what are we going to do? Are we going to create ten objects of integer class?

The answer is no, because we want to create one Ruby array object and store variables into it. This way the variables don’t need to be named time and again, they don’t get messed up, we can refer to them easily and we won’t have to write redundant piece of code if we want some calculation to be performed into it. Instead we can write one function for a ruby array and loop through the data items and perform operations like sorting, searching etc.

Object types Ruby array can hold:

  • Strings
  • Numbers
  • Other arrays
  • Mixed types
  • Hash

While creating array object, Ruby creates an instance of ArrayClass to create array object. You can verify this by creating an object and querying with class? Method.

Array = [];

Array.class? # Returns ArrayClass
How to create Ruby array?

First let’s create an empty array:

My_array = [];

Now let’s create Ruby array of strings:


Similarly Ruby array of numbers:



Access elements of array

Array_name[0] # Returns first item of Ruby array

Array_name[1] # Returns second item of Ruby array

Array_name[n] # Returns (n+1)th item from Ruby array.   



All Ruby array are indexed starting from 0 not 1.

If the item does not exist in that particular index, it returns nil.


Insert and Update items of Ruby Array

Array_name[3] = 4 # It sets the value 4 at the 3rd position of array, if the value already exists it updates the value.

Array_name << 4 # This is another way of adding value in array but it appends the item at last position of array aka append operation.


Delete items of Ruby Array

Array_name.clear # Deletes all the items from array

Array_name = nil # Sets array_name to nil. But remember nil and empty array are different things. Use clear if you just want to remove data.

array_name.delete(item) # deletes the item from array , remember not index.

array_name.delete_at(index) # deletes item from array by index


More On Ruby Array

>> array = [1,2,3,4,5] # Integer type array


>> array.first # Returns first item of array

>> 1


>> array.last # Returns last item of array

>> 5


>> array1 = [1,3,[“Rose”,”Jasmine”],34.56] # Mixed type array

>> puts array.inspect #Returns string version of array remember only printing array does not return string version

>> ”[1,2,3,4,5”]”


>>  array.join # Join the whole array also array.to_s also does the same thing

>> “12345”


>> array.join(“,”) # Join with comma

>> “1,2,3,4,5”


>> x = “a,b,c,d,e”

>> x.split(“,”) # Find comma, turn into string and put into array

>> [“a”,”b”,”c”,”d”,”e”]


>> array.reverse

>> [5,4,3,2,1]


>> data = [4,3,5,2,6,7,7]

>> data.sort # Sort data items

>> [2,3,4,5,6,7,7]


>> data.uniq # Returns only the unique value from array, no duplication

>> [2,3,4,5,6,7]


>> data.push(3) # Same as append

>> [4,3,5,2,6,7,7,3]

>> data.pop # Pop the last item from array


>> data.shift # Same as pop but from starting index, remember not last

>> data.unshift(1) #Push item 1 at starting position of array


>> data + [9,10] # Merge array with + operator

>> [4,3,5,2,6,7,7,9,10]


>> data.include?(100) # Check if 100 is present in the array or not

>> false


>> numbers = [3,4.5]

>> numbers.sum # Find sum of numbers in array



>> my_numbers = Array(0..100) # Easiest way to create array of sequence, the .. operator takes two two parameters one starting at left and ending at right.


>> my_bio = [ [“Name”,”Rabin” ], [“Age”,22]]

>> my_bio.to_h # This method is used to convert array to hash data structure

>> {“Name”=>”Rabin”, “Age”=>22}


Array Iteration

Iteration is the important task we need to perform while programming. We have several techniques to loop over items in Ruby array but let’s see some of them

array = [1,2,3]

array.each { |x| puts x } # Prints array items one by one


my_fav_movies = [“Star Wars”,”Notebook”,”The Terminator”]


my_fav_movies.each_with_index do |movie, index|
 puts “#{index} I like #{movie}!”
=> 0 I like Star Wars
=> 1 I like Notebook
=> 2 I like The Terminator


Array Map

Ruby array has a special method called .map that calls a block for each item and returns the new array based on the output of the block. Consider the following example

cities = [“NYC”,”LA”,”Kathmandu”]

travel_cities = do |city|

“Beautiful #{ city }”



Now, the travel_cities variable is a Ruby array. If you print out the value of this variable you will get the following output.


>> [“Beautiful NYC”,”Beautiful LA”,”Beautiful Kathmandu”]


Complexity of Ruby Array

Insertion => O(1) because we just get the position to store value and store it

Delete => O(1) because we delete item by index

Update => O(1) update value into index

Unshift => O(n) because we need to move the whole items backwards in array

Shift => O(1) just pop the first element

Access => O(1)


Important points to consider:

  1. If you give the array index as negative, it starts the counting from reverse order for example index -1 counts the last item of ruby array.



Ruby array are very powerful data structure. They have the special capabilities of nesting and mixing other data structures. We need to be very careful when we are applying methods on those arrays. All of the methods are not possible to mention here. We can check what methods are possible within the data structure by .methods query. It returns a bunch of methods that are possible within the data structure. We can also build other data structures from ruby data structure. For example we can build matrix data structure with the help of multi dimensional array. Another example is we can use arrays to create graph data structure. We can create nodes and edges with it. So it is the foundational  and building blocks of other data structures.