0
0
Rubyprogramming~5 mins

Accessing elements (indexing, first, last) in Ruby

Choose your learning style9 modes available
Introduction

We use indexing to get specific items from a list or string. It helps us find the first, last, or any element easily.

You want to get the first name from a list of names.
You need the last character of a word.
You want to find the third item in a shopping list.
You want to check the first or last element in an array quickly.
Syntax
Ruby
array[index]
array.first
array.last
string[index]
string[0]  # first character
string[-1] # last character

Indexing starts at 0, so the first element is at index 0.

Negative indexes count from the end: -1 is last, -2 is second last, and so on.

Examples
Get the first and last fruits from the array.
Ruby
fruits = ["apple", "banana", "cherry"]
puts fruits[0]    # apple
puts fruits.first # apple
puts fruits.last  # cherry
Access the first and last characters of a string.
Ruby
word = "hello"
puts word[0]    # h
puts word[-1]   # o
Get the third element (index 2) from the numbers array.
Ruby
numbers = [10, 20, 30, 40]
puts numbers[2]  # 30
Sample Program

This program shows how to get the first, last, and specific elements from arrays and strings.

Ruby
colors = ["red", "green", "blue", "yellow"]

puts "First color: #{colors.first}"
puts "Last color: #{colors.last}"
puts "Second color: #{colors[1]}"

word = "ruby"
puts "First letter: #{word[0]}"
puts "Last letter: #{word[-1]}"
OutputSuccess
Important Notes

Remember, arrays and strings both use zero-based indexing.

Using negative indexes is a quick way to get elements from the end.

If you try to access an index that does not exist, Ruby returns nil without error.

Summary

Use [index] to get any element by position.

.first and .last give the first and last elements easily.

Negative indexes count from the end, making it easy to get last elements.