Ruby Tutorial

Arrays

Ordered collections, push/pop, and negative indexing

Creating Arrays

An Array in Ruby is an ordered list of elements. They can contain any mix of types, but usually they store items of the same type.
ruby
fruits = ["Apple", "Banana", "Cherry"]

Negative Indexing

Wait! Ruby has a cool feature: Negative Indexing. -1 refers to the last item, -2 to the second to last, and so on.
ruby
puts fruits[-1] # "Cherry"

Array Manipulation

MethodActionDescription
push / <<AddAppend item to the end
popRemoveRemove the last item
shiftRemoveRemove the first item
unshiftAddAppend item to the front
sortLogicReturns a new sorted array
uniqFilterReturns an array with no duplicates

Combined Arrays

You can add or subtract arrays just like numbers!
ruby
[1, 2] + [3, 4] # [1, 2, 3, 4]
[1, 2, 3] - [2]  # [1, 3]

Helpful Shorthand (%w)

If you want an array of strings, you don't need all the quotes and commas. Use the %w shorthand.
ruby
words = %w[apple banana cherry] # Same as ["apple", "banana", "cherry"]

Summary

TermDescription
[]Bracket notation for access
<<The "Shovel" operator for appending
lengthNumber of items in the array
empty?Check if array is empty
include?Check if value exists in array
Best ForOrdered lists, stacks, and queues
LogicDynamic and grows as needed
SafetyReturns nil if you access an index that doesn't exist
ModernArrays in Ruby 3.x are highly optimized for speed
StandardUse each to iterate, not a for loop
IdentityArrays are objects of the Array class