Recall & Review
beginner
What does the
times method do in Ruby?The
times method runs a block of code a specific number of times, based on the integer it is called on.Click to reveal answer
beginner
How do you use
times to print "Hello" 3 times?You write
3.times { puts "Hello" }. This runs the puts "Hello" command 3 times.Click to reveal answer
intermediate
What value does the block variable in
times represent?The block variable represents the current count, starting from 0 up to one less than the number. For example, in
5.times { |i| puts i }, i goes from 0 to 4.Click to reveal answer
intermediate
What is the return value of the
times method?The
times method returns the original integer it was called on. For example, 3.times { puts "Hi" } returns 3.Click to reveal answer
advanced
Can
times be used without a block? What happens?If
times is called without a block, it returns an Enumerator. This lets you chain other methods or use it later.Click to reveal answer
What does
4.times { |i| puts i } print?✗ Incorrect
The block variable
i starts at 0 and goes up to 3, so it prints 0, 1, 2, 3 each on a new line.What is the return value of
5.times { puts "Hi" }?✗ Incorrect
The
times method returns the integer it was called on, which is 5.What happens if you call
3.times without a block?✗ Incorrect
Without a block,
times returns an Enumerator object.Which of these is a correct way to repeat a task 2 times?
✗ Incorrect
The correct Ruby method to repeat a block a number of times is
times called on an integer.In
n.times { |i| ... }, what is the first value of i?✗ Incorrect
The block variable
i starts at 0 and increments by 1 each iteration.Explain how the
times method works in Ruby and give an example.Think about how many times the code inside the block runs and what the block variable represents.
You got /3 concepts.
What happens if you call
times without a block? How can this be useful?Consider what Ruby returns when no block is given and how you might use that.
You got /3 concepts.