0
0
Rubyprogramming~15 mins

For loop (rarely used in Ruby) - Mini Project: Build & Apply

Choose your learning style9 modes available
For loop (rarely used in Ruby)
📖 Scenario: You are helping a small bookstore organize its inventory. The store wants to list the names of some popular books it has in stock.
🎯 Goal: You will create a list of book titles, set up a counter for counting books, use a for loop to go through each book, and finally print each book's name.
📋 What You'll Learn
Create an array called books with the exact titles: 'The Hobbit', '1984', 'Pride and Prejudice'
Create a variable called count and set it to 0
Use a for loop with the variable book to iterate over books
Inside the loop, increment count by 1
Inside the loop, print the current book
After the loop, print the total number of books using count
💡 Why This Matters
🌍 Real World
Bookstores and libraries often need to list and count books in their inventory. Using loops helps automate this task.
💼 Career
Knowing how to loop through lists and count items is a basic skill for many programming jobs, including data processing and software development.
Progress0 / 4 steps
1
Create the list of books
Create an array called books with these exact titles: 'The Hobbit', '1984', 'Pride and Prejudice'
Ruby
Need a hint?

Use square brackets [] to create an array and separate items with commas.

2
Set up a counter
Create a variable called count and set it to 0
Ruby
Need a hint?

Just write count = 0 to start counting from zero.

3
Use a for loop to go through each book
Use a for loop with the variable book to iterate over books. Inside the loop, increase count by 1 and print the current book
Ruby
Need a hint?

Use for book in books to start the loop, count += 1 to add one, and puts book to print.

4
Print the total number of books
After the loop, print the total number of books using count with puts
Ruby
Need a hint?

Use puts "Total books: #{count}" to show the total count.