0
0
Rubyprogramming~5 mins

Array modification (push, pop, shift, unshift) in Ruby

Choose your learning style9 modes available
Introduction

We use array modification methods to add or remove items from a list easily. This helps us change the list without making a new one.

When you want to add a new item to the end of a list, like adding a new song to a playlist.
When you want to remove the last item from a list, like taking the last book off a shelf.
When you want to remove the first item from a list, like serving the first customer in line.
When you want to add a new item to the front of a list, like putting a new task at the top of your to-do list.
Syntax
Ruby
class Array
  # Add item to the end
  def push(item)
    self[self.length] = item
    self
  end

  # Remove last item
  def pop
    return nil if self.empty?
    last_item = self[-1]
    self.delete_at(-1)
    last_item
  end

  # Remove first item
  def shift
    return nil if self.empty?
    first_item = self[0]
    self.delete_at(0)
    first_item
  end

  # Add item to the front
  def unshift(item)
    self.insert(0, item)
    self
  end
end

These methods change the original array directly.

push and unshift add items; pop and shift remove items.

Examples
Adding an item to an empty array using push.
Ruby
my_array = []
my_array.push(10)
# my_array is now [10]
Removing the only item with pop results in an empty array.
Ruby
my_array = [5]
removed = my_array.pop
# removed is 5
# my_array is now []
Removing the first item shifts the rest left.
Ruby
my_array = [1, 2, 3]
first_item = my_array.shift
# first_item is 1
# my_array is now [2, 3]
Adding an item to the front with unshift.
Ruby
my_array = [2, 3]
my_array.unshift(1)
# my_array is now [1, 2, 3]
Sample Program

This program shows how to add and remove items from an array using push, pop, shift, and unshift. It prints the array before and after each change.

Ruby
my_array = ["apple", "banana", "cherry"]

puts "Original array: #{my_array}"

# Add to end
my_array.push("date")
puts "After push('date'): #{my_array}"

# Remove last
removed_last = my_array.pop
puts "After pop(): #{my_array}, removed: #{removed_last}"

# Remove first
removed_first = my_array.shift
puts "After shift(): #{my_array}, removed: #{removed_first}"

# Add to front
my_array.unshift("apricot")
puts "After unshift('apricot'): #{my_array}"
OutputSuccess
Important Notes

Time complexity: push and pop are fast (O(1)), shift and unshift can be slower (O(n)) because they move many items.

Space complexity is usually O(1) since changes happen in place.

Common mistake: expecting shift and unshift to be as fast as push and pop, but they move all elements.

Use push/pop when working with the end of the list, and shift/unshift when working with the start.

Summary

push adds an item to the end of an array.

pop removes the last item and returns it.

shift removes the first item and returns it.

unshift adds an item to the front of an array.