Reputation: 988
I'm working on some app academy practice questions and I can't seem to print two 00's for my time conversion. Here's what I have so far:
def time_conversion(minutes)
hours = minutes/60
if minutes%60 < 10
minutes = minutes%60
elsif minutes%60 > 10
minutes = minutes%60
elsif minutes%60 == 0
minutes = 00
end
return "#{hours}:#{minutes}"
end
time_conversion(360)
Upvotes: 4
Views: 203
Reputation: 122383
You can use sprintf
:
sprintf("%02d:%02d", hours, minutes)
or the equivalent String#%
"%02d:%02d" % [hours, minutes]
Upvotes: 6
Reputation: 110675
The method Fixnum#divmod is useful here:
def time_conversion(minutes)
"%d hours: %02d minutes" % minutes.divmod(60)
end
time_conversion(360)
#=> "6 hours: 00 minutes"
Upvotes: 0
Reputation: 1534
A very simple re-structuring of your code could be with one single line in your function def -
return "#{m/60}:#{m%60 == 0 ? '00' : m%60}"
Sample execution from irb -
2.1.5 :077 > m=100
=> 100
2.1.5 :078 > puts "#{m/60}:#{m%60 == 0 ? '00' : m%60}"
1:40
=> nil
2.1.5 :079 > m=120
=> 120
2.1.5 :080 > puts "#{m/60}:#{m%60 == 0 ? '00' : m%60}"
2:00
=> nil
2.1.5 :081 >
Upvotes: 1
Reputation: 15985
replace last statement of time_conversion
with return "%02d:%02d" % [ hours, minutes ]
Check the document http://ruby-doc.org/core-2.1.5/String.html#method-i-25 for more details
Upvotes: 0