0
0
RubyHow-ToBeginner · 3 min read

How to Add Element to Array in Ruby: Simple Syntax and Examples

In Ruby, you can add an element to an array using array.push(element) or the shovel operator array << element. Both add the element to the end of the array, while array.unshift(element) adds it to the beginning.
📐

Syntax

Here are the common ways to add elements to a Ruby array:

  • array.push(element): Adds element to the end of array.
  • array << element: Shovel operator, also adds element to the end.
  • array.unshift(element): Adds element to the beginning of array.
ruby
array = [1, 2, 3]
array.push(4)      # Adds 4 at the end
array << 5          # Adds 5 at the end
array.unshift(0)    # Adds 0 at the beginning
💻

Example

This example shows how to add elements to an array using push, the shovel operator, and unshift. It prints the array after each addition.

ruby
numbers = [10, 20, 30]
numbers.push(40)
puts numbers.inspect  # Output: [10, 20, 30, 40]
numbers << 50
puts numbers.inspect  # Output: [10, 20, 30, 40, 50]
numbers.unshift(5)
puts numbers.inspect  # Output: [5, 10, 20, 30, 40, 50]
Output
[10, 20, 30, 40] [10, 20, 30, 40, 50] [5, 10, 20, 30, 40, 50]
⚠️

Common Pitfalls

One common mistake is trying to add elements using array + element, which does not modify the original array but returns a new array. Also, using push or << with multiple arguments requires an array, not separate values.

Wrong way:

arr = [1, 2]
arr + 3  # Does not add 3 to arr, returns a new array

Right way:

arr.push(3)  # Modifies arr by adding 3
ruby
arr = [1, 2]
new_arr = arr + [3]
puts arr.inspect      # Output: [1, 2]
puts new_arr.inspect  # Output: [1, 2, 3]

arr.push(3)
puts arr.inspect      # Output: [1, 2, 3]
Output
[1, 2] [1, 2, 3] [1, 2, 3]
📊

Quick Reference

MethodDescriptionExample
pushAdds element(s) to the endarray.push(4)
<< (shovel)Adds one element to the endarray << 5
unshiftAdds element(s) to the beginningarray.unshift(0)
+ operatorReturns new array by concatenationnew_array = array + [6,7]

Key Takeaways

Use push or << to add elements at the end of an array.
Use unshift to add elements at the beginning of an array.
The + operator returns a new array and does not modify the original.
Avoid adding elements with array + element as it does not change the original array.
The shovel operator << is a concise and common way to add one element.