Challenge - 5 Problems
Array Sorting and Reversing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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(",")
Attempts:
2 left
💡 Hint
Think about what sort and reverse do to the array.
✗ Incorrect
The code sorts the array in ascending order: [1,3,5,8], then reverses it to descending order: [8,5,3,1], then joins elements with commas.
❓ Predict Output
intermediate2: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]
Attempts:
2 left
💡 Hint
Sort alphabetically, then reverse, then pick first element.
✗ Incorrect
Sorting alphabetically gives ["bird", "cat", "dog"]. Reversing gives ["dog", "cat", "bird"]. The first element is "dog".
🔧 Debug
advanced2: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
Attempts:
2 left
💡 Hint
Check what sort and reverse! do to the array.
✗ Incorrect
sort returns a new sorted array [1,2,3]. reverse! reverses that new array in place to [3,2,1]. The original arr remains [1,2,3], so puts arr prints 1
2
3 each on a new line. No runtime error.
🧠 Conceptual
advanced2: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 }
Attempts:
2 left
💡 Hint
Sort, reverse, then select elements greater than 5.
✗ Incorrect
Sorted ascending: [2,4,7,9], reversed: [9,7,4,2], select >5: [9,7], so 2 elements.
❓ Predict Output
expert3: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("-")
Attempts:
2 left
💡 Hint
Convert all elements to integers for sorting, then reverse.
✗ Incorrect
to_i converts strings to integers: [10,2,3,1]. Sorted ascending: [1,2,3,10]. Reversed: [10,3,2,1]. Joined with '-' gives "10-3-2-1".