📖 Scenario: You work in a small bookstore. You have a list of book titles that customers want to buy. You want to organize this list to make it easier to find books.
🎯 Goal: You will create a list of book titles, then sort them alphabetically, and finally reverse the order to see the list from Z to A.
📋 What You'll Learn
Create an array called books with the exact titles: 'Ruby Basics', 'Learn Rails', 'JavaScript Guide', 'Python Essentials', 'Data Science'
Create a variable called sorted_books that holds the books array sorted alphabetically
Create a variable called reversed_books that holds the sorted_books array reversed
Print the reversed_books array
💡 Why This Matters
🌍 Real World
Sorting and reversing lists is common when organizing data like product names, customer lists, or any collection of items.
💼 Career
Many programming jobs require you to manipulate lists and arrays efficiently to prepare data for display or further processing.
Progress0 / 4 steps
1
Create the initial array of book titles
Create an array called books with these exact titles: 'Ruby Basics', 'Learn Rails', 'JavaScript Guide', 'Python Essentials', 'Data Science'
Ruby
Hint
Use square brackets [] to create an array and separate each title with commas.
2
Sort the array alphabetically
Create a variable called sorted_books that holds the books array sorted alphabetically using the sort method
Ruby
Hint
Use sorted_books = books.sort to get a new sorted array.
3
Reverse the sorted array
Create a variable called reversed_books that holds the sorted_books array reversed using the reverse method
Ruby
Hint
Use reversed_books = sorted_books.reverse to reverse the sorted list.
4
Print the reversed array
Print the reversed_books array using puts
Ruby
Hint
Use puts reversed_books to print each book title on its own line.
Practice
(1/5)
1. What does the Ruby method sort do when called on an array?
easy
A. It arranges the elements in ascending order.
B. It reverses the order of elements.
C. It removes duplicate elements.
D. It shuffles the elements randomly.
Solution
Step 1: Understand the purpose of sort
The sort method arranges elements in ascending order by default.
Step 2: Compare with other methods
Unlike reverse which flips order, sort orders elements from smallest to largest.
Final Answer:
It arranges the elements in ascending order. -> Option A
Quick Check:
sort = ascending order [OK]
Hint: Remember: sort arranges ascending, reverse flips order [OK]
Common Mistakes:
Confusing sort with reverse
Thinking sort removes duplicates
Assuming sort shuffles elements
2. Which of the following is the correct syntax to reverse an array arr in Ruby?
easy
A. arr.reverse!
B. arr.reverse[]
C. reverse.arr()
D. arr.reverse()!
Solution
Step 1: Identify the correct method call
The method to reverse an array in place is reverse! called on the array object.
Step 2: Check syntax correctness
Only arr.reverse! is valid Ruby syntax; others are incorrect method calls or misplaced symbols.