0
0
Rubyprogramming~20 mins

Sort_by for custom sorting in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Sort_by Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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(",")
Apear,fig,apple,banana
Bfig,pear,apple,banana
Cfig,apple,pear,banana
Dbanana,apple,pear,fig
Attempts:
2 left
💡 Hint
Think about sorting words by their length from shortest to longest.
Predict Output
intermediate
2: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("")
Abac
Babc
Ccab
Dbca
Attempts:
2 left
💡 Hint
Look at the price values and sort from lowest to highest.
🔧 Debug
advanced
2: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(",")
ATypeError: no implicit conversion of Symbol into Integer
BNo error, outputs: 9,4,7,2
CArgumentError: wrong number of arguments (given 0, expected 1)
DSyntaxError: unexpected end-of-input, expecting expression
Attempts:
2 left
💡 Hint
Check the block syntax and the use of the modulo operator.
Predict Output
advanced
2: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(",")
Abanana,fig,apple,pear
Bfig,banana,apple,pear
Cbanana,fig,pear,apple
Dapple,pear,banana,fig
Attempts:
2 left
💡 Hint
Sort first by count ascending, then by fruit name ascending.
🧠 Conceptual
expert
3: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("")
Aabc a (sort_by sorts but reverses equal elements order)
Baa bc (sort_by is unstable, order of equal elements may change)
Caabc (sort_by is stable, original order of equal elements preserved)
Dcbaa (sort_by sorts descending)
Attempts:
2 left
💡 Hint
Think about whether sort_by keeps the order of elements that compare equal.