Some Useful Ruby Methods
Understand how Ruby's sleep method controls program delays and why it's used mainly in testing. Compare Ruby's synchronous execution with JavaScript's asynchronous behavior using callbacks. Learn the importance of grasping synchronous programming before working with JavaScript to avoid nested callback issues.
We'll cover the following...
Recall this program from the previous chapter:
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 testing ...