0
0
Rubyprogramming~15 mins

Accessing elements (indexing, first, last) in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Accessing elements (indexing, first, last)
📖 Scenario: You are helping a small bookstore organize a list of book titles. You want to practice how to get specific books from the list by their position.
🎯 Goal: Learn how to access elements in a list by using index numbers, and how to get the first and last items easily.
📋 What You'll Learn
Create a list of book titles with exact names
Create a variable to hold the index number to access
Use the index to get the correct book from the list
Print the first book, the book at the index, and the last book
💡 Why This Matters
🌍 Real World
Accessing elements by position is common when working with lists of items like books, songs, or products.
💼 Career
Knowing how to get specific data from lists is a basic skill for programming jobs that handle collections of information.
Progress0 / 4 steps
1
Create the list of books
Create an array called books with these exact titles in this order: 'The Hobbit', '1984', 'Pride and Prejudice', 'To Kill a Mockingbird', 'The Great Gatsby'
Ruby
Need a hint?

Use square brackets [] to create the array and separate titles with commas.

2
Set the index to access
Create a variable called index and set it to 2 to choose the third book in the list
Ruby
Need a hint?

Remember, arrays start counting at 0, so 2 means the third item.

3
Access the book at the index
Create a variable called selected_book and set it to the book at position index in the books array
Ruby
Need a hint?

Use square brackets with the variable index to get the book.

4
Print first, selected, and last books
Print the first book using books.first, the selected book using selected_book, and the last book using books.last each on its own line
Ruby
Need a hint?

Use puts to print each book on its own line.