Why Inputing "#" in "gets.chomp.to_i" won't crash the code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why Inputing "#" in "gets.chomp.to_i" won't crash the code?

I noticed that even if the input of first_num and secone_num had a hash sign(#) in it, the code still runs correctly. Ex: If the input was : 5 #3 * 6 #2 done The output will be: 5*6=30 But if the operator input had a hash sign ex : * #+ it is printed and the code won't execute correctly(even though it shows no Errors). I am confused 🤕 Why it works? Why no error was raised? Why the second try didn't work? And why no error was raised in the second try? https://code.sololearn.com/ciE5vXdom3Eh/?ref=app

16th Mar 2018, 8:23 PM
Ammar Darwish
Ammar Darwish - avatar
2 Answers
+ 4
The to_i method returns an integer no matter what. Input of '#' would yield a 0, '5#' a 5. It stops looking at the first non-digit and returns whatever it did find. Your operator string can only be matched to your test string exactly. Anything extra and it fails. Therefore, no math is performed.
17th Mar 2018, 1:24 AM
John Wells
John Wells - avatar
+ 2
@John Wells Thank you, sir. I get it now
17th Mar 2018, 6:39 AM
Ammar Darwish
Ammar Darwish - avatar