0

Please see the following code (taken from Learning Ruby book):

def timer(start)
  puts "Minutes: " + start.to_s
  start_time = Time.now
  puts start_time.strftime("Start time: %I:%M:%S: %p")
  start.downto(1) { |i| sleep 60 }
  end_time = Time.now
  print end_time.strftime("Elapsed time: %I:%M:%S: %p\n")
end

timer 10

Why would there be a need to change the start variable into a string on the puts line? Couldn't I, for example, simply put in puts "Minutes: #{start}"?

Also, the start.downto(1) line: Is the block {|i| sleep 60} specifying how many seconds a minute should be?

4
  • It's only required if you want to see the time in a nice format with "Start time:..." etc in front of it, or if you want a specific date/time format. Commented Jan 8, 2014 at 17:31
  • I suspect you mean def timer(start). Reply not required, as I'll be deleting this comment. Commented Jan 8, 2014 at 17:34
  • Here is the documentation for Kernel#sleep. Note that { |i| sleep 60 } can be written { sleep 60 }, since the iterator variable i is not used. Commented Jan 8, 2014 at 17:48
  • I found that example on page 58 of the book you reference. As I had suspected, def timer should be def timer(start). Please correct that. Commented Jan 8, 2014 at 18:05

1 Answer 1

2

Yes, you can also say:

puts "Mintues: #{start}"

It's one of many nice Ruby choices. :) In this case, it doesn't make much difference.

Regarding the loop:

start.downto(1) { |i| sleep 60 }

Yes, this is counting minutes down to 1 and each time is sleeping 60 seconds. So it will sleep for start minutes. If start isn't too large, you could just use sleep 60*start.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.