0
0
Rubyprogramming~5 mins

Times method for counted repetition in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A1 2 3
B1 2 3 4
C4 3 2 1
D0 1 2 3
What is the return value of 5.times { puts "Hi" }?
Anil
BAn array of 5 elements
C5
D"Hi"
What happens if you call 3.times without a block?
AIt returns an Enumerator
BIt raises an error
CIt returns nil
DIt prints 3 times
Which of these is a correct way to repeat a task 2 times?
A2.repeat { do_something }
B2.times { do_something }
Ctimes(2) { do_something }
Drepeat(2) { do_something }
In n.times { |i| ... }, what is the first value of i?
A0
B1
Cn
Dnil
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.