Notifications
Clear all
Topic starter 01/08/2025 11:19 pm
Ruby arrays are like flexible containers that hold collections of items—think of them as magical baskets that can carry anything from numbers to strings to other arrays 🧺✨
🧱 Creating an Array
You can create an array using square brackets:
fruits = ["apple", "banana", "cherry"]
Or with the Array.new
method:
numbers = Array.new(3, 0) # [0, 0, 0]
Ruby arrays can hold mixed types:
mixed = [42, "hello", true]
🔍 Accessing Elements
Ruby arrays are zero-indexed, meaning the first item is at index 0
:
puts fruits[0] # "apple"
puts fruits[-1] # "cherry" (last item)
You can also use ranges and slices:
puts fruits[1..2] # ["banana", "cherry"]
🛠️ Common Array Methods
Method | Description |
---|---|
push / << |
Add item to the end |
pop |
Remove last item |
shift |
Remove first item |
unshift |
Add item to the beginning |
include? |
Check if item exists |
sort |
Sort items |
reverse |
Reverse the array |
uniq |
Remove duplicates |
join |
Convert array to string |
each |
Loop through items |
Example:
fruits.each do |fruit|
puts "I love #{fruit}!"
end
🧬 Nested Arrays
Arrays can contain other arrays:
matrix = [[1, 2], [3, 4]]
puts matrix[0][1] # Output: 2
🧠 Bonus: Word Arrays
Ruby has a shortcut for arrays of strings:
days = %w[Monday Tuesday Wednesday]
Same as:
days = ["Monday", "Tuesday", "Wednesday"]