/ RAILS

Difference between Array Push and Array Insert

As we all know there are more than one way of doing the same thing in the Ruby. Thus, it becomes more important to choose the right way so that it does not affect your Performance

Now, let us discuss about Arrays in Ruby.

=> Array is collection of entities

=> Array can be the collection of different type of objects like, integers, strings, hashes, symbols etc.

=> Methods: There are many inbuilt methods that come in handy for doing particular task

=> One can create Array and get list of the methods that can be called on Array object in Ruby by following command,

Creating Empty Array

array = Array.new   # where array is name of object

Listing Methods on Array

array.methods.sort # where array is object of Array class

=> Explore the various methods on Array class.

=> You can refer documentation of Ruby Array here.

Array Push and Array Insert

array = [] # Another way of creating an Array

=> We can insert an element is Array by,

array << 4 # Inserted element 4 in the Array, thus it will be,  [4]

=> We can also push element in the Array by,

array.push(5)  
# Pushed (Ultimately inserted) element in the Array, thus it  will be, [4,5]

Both of the methods look exactly same and ultimately they achieve the same result of pushing/inserting an element in the array. But, the difference is

 => Array.push  can be used to insert more than one element in Array at a time. e.g.

array.push(1,2,3)

while,

=> Insertion operator («) can be used to insert only one element at a time in the Array.

Performance Consideration:

If we consider performance, then

Case: Want to add single element in the Array => Prefer using Insertion Operator(«) than using Array.push method. Benchmarking proves the Fact.

Case: Want to add multiple elements in Array => You can prefer Array.push method.

That was all regarding Array Push and Insert, play with methods of Array object to get familiar with. We will get to know about Benchmarking in our upcoming post.

Comments and Suggestions are Welcome!

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee