here's a practice question - Write a method that will take in a number of minutes, and returns a string that formats the number into hours:minutes
.
def time_conversion(minutes)
hours = minutes / 60
mins = minutes % 60
time = hours + ":" + mins
return time
end
the following are tests to see if this works. if they return true then it means my code works correctly.
puts('time_conversion(15) == "0:15": ' + (time_conversion(15) == '0:15').to_s)
puts('time_conversion(150) == "2:30": ' + (time_conversion(150) == '2:30').to_s)
puts('time_conversion(360) == "6:00": ' + (time_conversion(360) == '6:00').to_s)
sometimes i get true for the first two tests but the third test line shows false even though the code will print out exactly the required.
other times I get the following error:
String can't be coerced into Fixnum (repl):4:in +' (repl):4:in
time_conversion' (repl):1:in `initialize'
please assist.
The error mainly refers to this line time = hours + ":" + mins
hours
& mins
are Fixnum
, whereas ":" is String
As the error message indicates, "String can't be coerced into Fixnum".
You could either do time = hours.to_s + ":" + minutes.to_s
or time = "#{hours}:#{minutes}"
.
因为Fixnum#+
采用Numeral
参数,而不是String
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.