Recall & Review
beginner Click to reveal answer
What does the
upto method do in Ruby?The
upto method counts from a starting number up to an ending number, running a block of code for each number in that range.beginner Click to reveal answer
How does the
downto method work in Ruby?The
downto method counts down from a starting number to an ending number, running a block of code for each number in that range.beginner Click to reveal answer
Example: What will this code print?
5.upto(7) { |n| puts n }It will print:
5
6
7
Because
5
6
7
Because
upto counts from 5 up to 7, printing each number.beginner Click to reveal answer
Example: What will this code print?
3.downto(1) { |n| puts n }It will print:
3
2
1
Because
3
2
1
Because
downto counts down from 3 to 1, printing each number.beginner Click to reveal answer
Can
upto and downto be used without a block?No, both methods require a block to tell Ruby what to do with each number in the count. Without a block, they do nothing.
What does
2.upto(4) { |n| puts n } print?✗ Incorrect
The
upto method counts up from 2 to 4, printing each number.Which method counts down from a number to a smaller number?
✗ Incorrect
downto counts down from a starting number to an ending number.What happens if you call
5.upto(3) { |n| puts n }?✗ Incorrect
Since 5 is greater than 3,
upto does not run the block and prints nothing.Which of these is true about
downto?✗ Incorrect
downto requires a block to specify what to do for each number.What will
1.upto(1) { |n| puts n } print?✗ Incorrect
It prints 1 because
upto includes the end number.Explain how the
upto method works and give a simple example.Think about counting forward like climbing stairs.
You got /3 concepts.
Describe the difference between
upto and downto methods.One goes up, the other goes down.
You got /4 concepts.
