Introduction To Ruby
Times
Every time we meet a new statement or structure in Ruby, we come across a cool alternative that is either easier, quicker to write or makes programming a little more natural than we expect. The times iterator is no exception.
Example 1
This example outputs the word 'Hello' exactly 5 times.
# times
5.times do
puts "Hello"
end
gets
Example 2
We can also use an iterator variable with our loop.
# times
5.times do |i|
puts "#{i} Hello"
end
gets
Make sure you check out the output of this program. It is a timely reminder that counting, in most programming languages, begins at 0.
Challenge
- Pick out some of the programs you wrote with for loops. Refactor them so that they use the times method.