Challenge - 5 Problems
Sort_by Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of custom sort_by with string length
What is the output of this Ruby code?
Ruby
words = ["apple", "pear", "banana", "fig"] sorted = words.sort_by { |word| word.length } puts sorted.join(",")
Attempts:
2 left
💡 Hint
Think about sorting words by their length from shortest to longest.
✗ Incorrect
The sort_by block returns the length of each word. The words are sorted from shortest to longest length: "fig" (3), "pear" (4), "apple" (5), "banana" (6).
❓ Predict Output
intermediate2:00remaining
Sorting hashes by a nested value using sort_by
What will this Ruby code print?
Ruby
items = [{name: "a", price: 10}, {name: "b", price: 5}, {name: "c", price: 20}]
sorted = items.sort_by { |item| item[:price] }
puts sorted.map { |i| i[:name] }.join("")Attempts:
2 left
💡 Hint
Look at the price values and sort from lowest to highest.
✗ Incorrect
The sort_by sorts hashes by their :price key ascending: 5 (b), 10 (a), 20 (c). So the names in order are "b", "a", "c".
🔧 Debug
advanced2:00remaining
Identify the error in this sort_by usage
This Ruby code is intended to sort numbers by their remainder when divided by 3. What error does it raise?
Ruby
numbers = [4, 9, 7, 2] sorted = numbers.sort_by { |n| n % } puts sorted.join(",")
Attempts:
2 left
💡 Hint
Check the block syntax and the use of the modulo operator.
✗ Incorrect
The code uses 'n %' which is incomplete syntax for modulo operation. Ruby expects an operand after '%'. This causes a SyntaxError.
❓ Predict Output
advanced2:00remaining
Custom sorting with multiple criteria using sort_by
What is the output of this Ruby code?
Ruby
data = [["apple", 2], ["banana", 1], ["pear", 2], ["fig", 1]] sorted = data.sort_by { |fruit, count| [count, fruit] } puts sorted.map(&:first).join(",")
Attempts:
2 left
💡 Hint
Sort first by count ascending, then by fruit name ascending.
✗ Incorrect
The sort_by sorts by count first: 1 then 2. For count=1, fruits are "banana", "fig" sorted alphabetically. For count=2, fruits are "apple", "pear" sorted alphabetically. So order is banana, fig, apple, pear.
🧠 Conceptual
expert3:00remaining
Understanding sort_by stability in Ruby
Given this Ruby code, what will be the output and why?
Ruby
arr = ["b", "a", "c", "a"] sorted = arr.sort_by { |x| x } puts sorted.join("")
Attempts:
2 left
💡 Hint
Think about whether sort_by keeps the order of elements that compare equal.
✗ Incorrect
Ruby's sort_by is stable, meaning elements that compare equal keep their original order. The two "a" elements remain in the same order as in the original array.