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:
# 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!'
The sleep
method takes one parameter: the number of seconds it should “sleep.” We can also specify fractional numbers. For example, 0.5, which is half of a second or 500 milliseconds.
Programmers usually don’t use the sleep
method in real programs, because programs should, by default, execute as fast as possible. However, they often use it while ...