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.
Array modification (push, pop, shift, unshift) in 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.
my_array = [] my_array.push(10) # my_array is now [10]
my_array = [5] removed = my_array.pop # removed is 5 # my_array is now []
my_array = [1, 2, 3] first_item = my_array.shift # first_item is 1 # my_array is now [2, 3]
my_array = [2, 3] my_array.unshift(1) # my_array is now [1, 2, 3]
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.
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}"
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.
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.