How can I make the variable minutes two digits?

I am trying to get the minutes to show two digits even though the definitive answer is assigned to the min_side variable. This is probably a simple answer, but I can't seem to get it to work.

def time_conversion(minutes)
hour = minutes/60
min_side = minutes%60
min_side = %02d

time = "#{hour}:#{min_side}"

return time
end

puts time_conversion(360)

      

+3


source to share


5 answers


You can use sprintf

:



def time_conversion(minutes)
  hour = minutes / 60
  min_side = minutes % 60

  sprintf("%d:%02d", hour, min_side)
end

      

+3


source


you can use rjust to add zeros



minutes.to_s.rjust(2, '0')

      

+1


source


You can do it like this:

 def time_conversion(minutes)
   "%d:%02d" % minutes.divmod(60)
 end

 puts time_conversion(360)
   #=> "6:00"

      

0


source


def time_conversion(minutes)
    hour = minutes/60
    min_side = minutes%60

    "#{hour}:#{min_side < 10 ? "0#{min_side}" : min_side}"
end

      

By the way, the last part of the last line is not a comment. It is a nested string interpolation that cannot recognize code formatting

0


source


Low readability, in place of the perl'ish way :)

time = "#{hour}:#{"0#{min_side}"[-2,2]}"

      

Adds zero and gets the last two characters of the result.

0


source







All Articles