0

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:intime_conversion' (repl):1:in `initialize'

please assist.

4
  • 1
    You can't add a number to a string. Run irb and enter 5 + 'foo', and you'll get the same error. Try time = hours.to_s + ':' + mins.to_s in your time_conversion function. Or even just replace the entire function contents with return "#{minutes/60}:#{minutes % 60}" Commented Apr 19, 2016 at 2:32
  • wow. that did the trick. I haven't come across using the hashes, but that's interesting. I suppose that allows me to remove the mins and hours variable Commented Apr 19, 2016 at 2:50
  • Yes you could remove those variables. You should look up "ruby string formatting" if you want to have leading zeroes in your minutes, like 6:05. Your time_conversion won't create 6:00. It will create 6:0. Commented Apr 19, 2016 at 2:51
  • aahhh yeaa. I need to add the leading zero if the minutes were less than 10. (as a string) but this is great. I'm loving all this. thanks! Commented Apr 19, 2016 at 3:00

2 Answers 2

1

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}".

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

3 Comments

yup, lurker pointed me to the same. I like the final suggestion there. it's nice and concise thanks!
thanks for the upvote,, actually my first ans on stackoverflow!
that's cool. see you on the other side when I'm up and running myself
0

Because Fixnum#+ takes a Numeral argument, not a String.

1 Comment

my first question here and I got a super fast reply. thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.