Ruby - Array Create, Add, and Remove Example

1. Introduction

Arrays are one of the fundamental data structures in Ruby, and they are used to store a collection of items. This post will guide you through creating an array, adding elements to it, and removing elements from it using Ruby.

2. Program Steps

1. Create a new array.

2. Add elements to the end of the array.

3. Add elements to the beginning of the array.

4. Remove elements from the end of the array.

5. Remove elements from the beginning of the array.

3. Code Program

# Initialize an empty array
arr = []
# Add elements to the end of the array using `push`
arr.push(1, 2, 3)
puts "After pushing 1, 2, 3: #{arr}"
# Add elements to the beginning of the array using `unshift`
arr.unshift(0)
puts "After unshifting 0: #{arr}"
# Remove an element from the end of the array using `pop`
removed_element = arr.pop
puts "After popping: #{arr} (Removed #{removed_element})"
# Remove an element from the beginning of the array using `shift`
removed_element = arr.shift
puts "After shifting: #{arr} (Removed #{removed_element})"

Output:

After pushing 1, 2, 3: [1, 2, 3]
After unshifting 0: [0, 1, 2, 3]
After popping: [0, 1, 2] (Removed 3)
After shifting: [1, 2] (Removed 0)

Explanation:

1. arr = []: Here, we initialize an empty array named arr.

2. arr.push(1, 2, 3): The push method allows us to add elements to the end of the array.

3. arr.unshift(0): The unshift method lets us add elements to the beginning of the array.

4. arr.pop: The pop method removes the last element from the array and returns it.

5. arr.shift: The shift method removes the first element from the array and returns it.

This post gives you a basic understanding of how to manipulate arrays in Ruby by adding or removing elements.


Comments