0
0
Rubyprogramming~20 mins

Array sorting and reversing in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Sorting and Reversing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code?
Consider the following Ruby code snippet. What will it print?
Ruby
arr = [5, 3, 8, 1]
puts arr.sort.reverse.join(",")
A"1,3,5,8"
B"8,5,3,1"
C"5,3,8,1"
D"8,3,5,1"
Attempts:
2 left
💡 Hint
Think about what sort and reverse do to the array.
Predict Output
intermediate
2:00remaining
What does this Ruby code print?
Look at this Ruby code. What will be printed?
Ruby
arr = ["dog", "cat", "bird"]
puts arr.sort.reverse[0]
A"error"
B"bird"
C"dog"
D"cat"
Attempts:
2 left
💡 Hint
Sort alphabetically, then reverse, then pick first element.
🔧 Debug
advanced
2:00remaining
Why doesn't this Ruby code sort and reverse the original array?
This Ruby code is intended to sort and reverse the original array in place, but the original array remains unchanged. What is the cause?
Ruby
arr = [1, 2, 3]
arr.sort.reverse!
puts arr
Asort returns a new array; reverse! modifies the new array but leaves the original unchanged
BNo error; code runs and prints "3\n2\n1"
Creverse! is not a valid method in Ruby
Dreverse! returns nil and causes puts to print nothing
Attempts:
2 left
💡 Hint
Check what sort and reverse! do to the array.
🧠 Conceptual
advanced
2:00remaining
How many elements are in the array after this Ruby code?
What is the number of elements in the array after running this code?
Ruby
arr = [4, 7, 2, 9]
new_arr = arr.sort.reverse.select { |x| x > 5 }
A1
B3
C4
D2
Attempts:
2 left
💡 Hint
Sort, reverse, then select elements greater than 5.
Predict Output
expert
3:00remaining
What is the output of this Ruby code with mixed types?
What will this Ruby code print?
Ruby
arr = ["10", 2, "3", 1]
sorted = arr.sort_by { |x| x.to_i }.reverse
puts sorted.join("-")
A"10-3-2-1"
B"error"
C"10-2-3-1"
D"3-10-2-1"
Attempts:
2 left
💡 Hint
Convert all elements to integers for sorting, then reverse.