0
0
RubyHow-ToBeginner · 3 min read

How to Access Elements in an Array in Ruby

In Ruby, you access an element in an array using its index inside square brackets like array[index]. Indexes start at 0, so array[0] gives the first element, and negative indexes count from the end, like array[-1] for the last element.
📐

Syntax

To get an element from an array, use array[index]. The index is a number showing the position of the element you want.

  • array: Your list of items.
  • index: Position number starting at 0 for the first item.
  • Negative index counts from the end: -1 is last, -2 is second last, and so on.
ruby
array = ["apple", "banana", "cherry"]
first = array[0]   # "apple"
last = array[-1]   # "cherry"
💻

Example

This example shows how to access the first, middle, and last elements of an array using positive and negative indexes.

ruby
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

puts fruits[0]    # first element
puts fruits[2]    # middle element
puts fruits[-1]   # last element
Output
apple cherry elderberry
⚠️

Common Pitfalls

Trying to access an index outside the array range returns nil instead of an error, which can cause bugs if not checked.

Remember that indexes start at 0, so array[1] is the second element, not the first.

ruby
arr = [10, 20, 30]

puts arr[3]    # nil, no error but no element
puts arr[-4]   # nil, negative index too far

# Correct way to check:
if arr[3].nil?
  puts "No element at index 3"
end
Output
nil nil No element at index 3
📊

Quick Reference

OperationSyntaxDescription
Access first elementarray[0]Gets the first item in the array
Access last elementarray[-1]Gets the last item in the array
Access nth elementarray[n]Gets the element at position n (0-based)
Out of range indexarray[index]Returns nil if index is outside array bounds

Key Takeaways

Use square brackets with an index to get an element from a Ruby array.
Indexes start at 0 for the first element and can be negative to count from the end.
Accessing an index outside the array returns nil, not an error.
Remember that array[1] is the second element, not the first.
Check for nil when accessing elements to avoid unexpected bugs.