Forum

Notifications
Clear all

Learn Ruby Arrays

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

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"]

 


   
Quote
Share: