Ruby Arrays
Arrays are Ruby's bread and butter. You can create one with Array.new or just use the literal syntax like [1, 2, 3]. They can hold mixed types โ numbers, strings, even other arrays all in the same list.
fruits = ["apple", "banana", "cherry"]
numbers = [42, "hello", 3.14, true]
# Adding and removing elements
fruits.push("dragonfruit")
fruits.pop
fruits.unshift("mango")
fruits.shift
Indexing works like you'd expect. Use [0] for the first element, [-1] for the last, and [1..3] for a slice.
fruits = ["apple", "banana", "cherry", "date"]
fruits[0] # => "apple"
fruits[-1] # => "date"
fruits[1..3] # => ["banana", "cherry", "date"]
Some handy methods for checking what's inside:
fruits.include?("apple") # => true
fruits.index("cherry") # => 2
fruits.length # => 4
And the powerful iterator methods for working with every element:
[1, 2, 3, 4].map { |n| n * 2 } # => [2, 4, 6, 8]
[1, 2, 3, 4].select { |n| n > 2 } # => [3, 4]
[1, 2, 3, 4].reject { |n| n > 2 } # => [1, 2]
[1, 2, 3].any? { |n| n > 2 } # => true
[1, 2, 3].all? { |n| n > 0 } # => true
[1, 2, 3].none? { |n| n > 5 } # => true
Try it Yourself ->