Ruby Arrays for Beginners
In Ruby, arrays are groups of elements that can include any data type, such as strings, integers, floats, or even other arrays. Understanding arrays enables you to create efficient and clear code. In this article, we will begin exploring arrays gradually.
What is an Array? (Simple Definition)
In simple terms: an array is a collection of elements.
Example: fruits = ["apple", "banana", "orange"]
This array holds 3 strings.
Arrays can also mix types: mixed = [1, "hello", 3.14, true]
How Indexing Works
Arrays use integer indexes starting from 0 (zero is the first element).
| Index | 0 | 1 | 2 |
|---|---|---|---|
| Array | “apple” | “banana” | “orange” |
Get element: fruits[0] # "apple"
Last element: fruits[-1] # "orange" (negative indexes count from end)
Creating Arrays
# Empty array
empty = []
# With elements
numbers = [1, 2, 3]
colors = %w[red green blue] # Shortcut for strings
# From range
evens = (2..10).to_a # [2, 3, 4, 5, 6, 7, 8, 9, 10]
Basic Operations
Example: fruits = ["apple", "banana", "orange"]
| Action | Code | Result |
|---|---|---|
| Add to end | fruits << "grape" |
fruits is now ["apple", "banana", "orange", "grape"] |
| Get length | fruits.length |
4 |
| Check empty | fruits.empty? |
false |
| First item | fruits.first |
"apple" |
| Last item | fruits.last |
"grape" |
Common Methods (Super Useful)
fruits = ["apple", "banana", "apple"]
# Loop through
fruits.each { |fruit| puts fruit }
# apple
# banana
# apple
# Find index
fruits.index("banana") # 1
# Remove duplicate
fruits.uniq # ["apple", "banana"]
# Sort
fruits.sort # ["apple", "apple", "banana"]
# Add multiple
fruits.push("mango", "pear") # Adds to end
Quick Example: Shopping List
cart = ["milk", "bread", "eggs"]
cart << "cheese" # Add item
puts "Buy: #{cart.join(', ')}" # Buy: milk, bread, eggs, cheese
puts "Total items: #{cart.length}" # Total items: 4
Arrays enhance the clarity and strength of your Ruby code. Rehearse these fundamentals, then investigate further options like map, choose, and remove. Begin with a simple task—make your initial array today.