Some Useful Ruby Methods
Learn about some useful Ruby methods, like sleep, in this lesson.
We'll cover the following...
Recall this program from the previous chapter:
Press + to interact
# Missile Launch Programputs 'Launching missiles...'5.downto(0) do |i|puts "#{i} seconds left"endputs 'Boom!'
sleep
method
This method counts from five to zero and displays a “Boom!” message. When the user runs this program, they get the results instantly because there is no delay. This method should count time in seconds, but all the programs run as fast as possible, unless they are told otherwise. Ruby doesn’t know that we count seconds because "seconds left"
is just a string. We can type any string we want to. So, we need to specify the real delay explicitly. Let’s do it now:
# Missile Launch Program using "sleep" Method puts 'Launching missiles...' 5.downto(0) do |i| puts "#{i} seconds left" sleep 1 end puts 'Boom!'
Missile launch program using the sleep method
The sleep
method takes one ...