Arrays & Array Methods
Ruby arrays are ordered, dynamically sized collections. They are highly flexible and can store multiple different data types simultaneously.
1 Dynamic Lists & Array Operations
Ruby arrays expand automatically and provide powerful list manipulation methods out-of-the-box: push, pop, shift, and unshift.
2 Array Operations Code
Let's run a program managing list items and sorting values:
Ruby — Arrays
▶ Run Code
# Declare array
items = ["Apple", "Banana", "Cherry"]
# Dynamic push
items << "Orange"
items.push("Peach")
# Array slicing [start, count]
subset = items[1, 2] # "Banana", "Cherry"
puts "Original Array: #{items.inspect}"
puts "Subset: #{subset.inspect}"
puts "Array length: #{items.length}"
puts "Sorted Array: #{items.sort.inspect}"
3 Code Challenge
Challenge: Write a program that declares a numerical array. Use array methods to delete duplicate values, sort it in descending order, and print the modified array.