Luukasama
Luukasama

Reputation: 3

Changing variable into string

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?

Upvotes: 0

Views: 59

Answers (1)

lurker
lurker

Reputation: 58324

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.

Upvotes: 2

Related Questions