Challenge - 5 Problems
Upto and Downto Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of using upto method
What is the output of the following Ruby code?
Ruby
result = [] 5.upto(7) { |i| result << i } puts result.join(",")
Attempts:
2 left
💡 Hint
Remember, upto counts from the starting number up to the ending number, including both.
✗ Incorrect
The upto method starts at 5 and counts up to 7, including both 5 and 7, so the array contains 5, 6, and 7.
❓ Predict Output
intermediate2:00remaining
Output of using downto method
What will this Ruby code print?
Ruby
result = [] 3.downto(1) { |i| result << i } puts result.join("-")
Attempts:
2 left
💡 Hint
Downto counts down from the starting number to the ending number, including both.
✗ Incorrect
The downto method starts at 3 and counts down to 1, so the array contains 3, 2, and 1.
🧠 Conceptual
advanced2:00remaining
Understanding return values of upto and downto
What is the return value of the following Ruby code snippet?
```ruby
result = 1.upto(3) { |i| puts i }
puts result
```
Attempts:
2 left
💡 Hint
The upto method returns the receiver after iteration.
✗ Incorrect
The upto method returns the starting number (receiver) after executing the block, so result is 1. But the code prints result, which is 1, after printing 1, 2, 3 inside the block.
❓ Predict Output
advanced2:00remaining
Output of combined upto and downto
What is the output of this Ruby code?
Ruby
output = [] 2.upto(3) { |i| output << i } 3.downto(2) { |i| output << i } puts output.join(",")
Attempts:
2 left
💡 Hint
The first loop counts up from 2 to 3, the second counts down from 3 to 2.
✗ Incorrect
The first loop adds 2 and 3, the second adds 3 and 2, so the array is [2,3,3,2].
❓ Predict Output
expert2:00remaining
Counting iterations with upto and downto
How many times will the block run in this Ruby code?
Ruby
count = 0 10.downto(7) { count += 1 } puts count
Attempts:
2 left
💡 Hint
Count how many numbers are between 10 and 7, including both.
✗ Incorrect
The downto method runs the block for 10, 9, 8, and 7, so 4 times.