Accessing Array Elements
Part of the Fundamentals section of Coddy's Ruby journey — lesson 59 of 88.
Each element in an array has a position called an index. In Ruby, indexing starts at 0, meaning the first element is at index 0, the second at index 1, and so on.
To access an element, use square brackets with the index:
fruits = ["apple", "banana", "cherry"]
puts fruits[0] # Outputs: apple
puts fruits[1] # Outputs: banana
puts fruits[2] # Outputs: cherryRuby also supports negative indexing, which counts from the end of the array. The index -1 refers to the last element, -2 to the second-to-last, and so on:
colors = ["red", "green", "blue"]
puts colors[-1] # Outputs: blue
puts colors[-2] # Outputs: greenYou can also use the first and last methods for quick access to the ends of an array:
numbers = [10, 20, 30, 40]
puts numbers.first # Outputs: 10
puts numbers.last # Outputs: 40If you try to access an index that doesn't exist, Ruby returns nil instead of raising an error:
letters = ["a", "b", "c"]
puts letters[10] # Outputs: (nothing - nil)Challenge
EasyYou are provided with the following array:
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]Read a single integer from input representing an index. Access the element at that index and print it.
Use negative indexing when the input is negative. The input will always be a valid index for this array (between -8 and 7).
After printing the element at the given index, print the first and last elements of the array on separate lines using the first and last methods.
For example, if the input is 2, the output should be:
Earth
Mercury
NeptuneIf the input is -1, the output should be:
Neptune
Mercury
NeptuneIf the input is 4, the output should be:
Jupiter
Mercury
NeptuneCheat sheet
Array elements are accessed using an index, which starts at 0:
fruits = ["apple", "banana", "cherry"]
puts fruits[0] # Outputs: apple
puts fruits[1] # Outputs: banana
puts fruits[2] # Outputs: cherryNegative indexing counts from the end of the array (-1 is the last element):
colors = ["red", "green", "blue"]
puts colors[-1] # Outputs: blue
puts colors[-2] # Outputs: greenUse first and last methods to access the first and last elements:
numbers = [10, 20, 30, 40]
puts numbers.first # Outputs: 10
puts numbers.last # Outputs: 40Accessing a non-existent index returns nil:
letters = ["a", "b", "c"]
puts letters[10] # Outputs: (nothing - nil)Try it yourself
# Array of planets
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
# Read the index from input
index = gets.chomp.to_i
# TODO: Write your code below
# 1. Access and print the element at the given index
# 2. Print the first element using the first method
# 3. Print the last element using the last methodThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input11Arrays
Creating ArraysAccessing Array ElementsModifying ArraysArray MethodsRecap - Product ArrayRecap - Reversed ArrayArray Shortcuts3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False