Array#prepend
arr.prepend(*objects) -> arr Returns:
Array · Updated March 13, 2026 · Array Methods arrays mutation elements
Array#prepend adds one or more elements to the beginning of an array, mutating it in place. It returns the same array object, allowing method chaining.
Syntax
array.prepend(*objects)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
*objects | Object | Required | One or more objects to add to the array |
Examples
Basic usage
queue = ["second", "third"]
queue.prepend("first")
queue
# => ["first", "second", "third"]
Adding multiple elements
numbers = [3, 4, 5]
numbers.prepend(1, 2)
numbers
# => [1, 2, 3, 4, 5]
Method chaining
result = [].prepend(2).prepend(1)
result
# => [1, 2]
Common Patterns
Queue implementation with prepend
queue = ["task2", "task3"]
queue.prepend("task1") # Add to front
queue.shift # => "task1"
Building a list in reverse order
items = []
items.prepend("third")
items.prepend("second")
items.prepend("first")
# => ["first", "second", "third"]
Edge Cases
Adding nil or false
arr = [1, 2]
arr.prepend(nil)
arr.prepend(false)
arr
# => [false, nil, 1, 2]
Adding to empty array
arr = []
arr.prepend("first")
arr
# => ["first"]
Adding mixed types
mixed = []
mixed.prepend(1, "two", :three)
mixed
# => [1, "two", :three]
Performance Notes
prepend mutates the array in place. However, it may require shifting all existing elements, making it O(n) in the worst case. For frequent front insertions, consider using a different data structure like a linked list.