← notes

gets.chomp.to_i returns 0, and beginners never find out

Nov 13, 2018

Work through Chris Pine's *Learn to Program* in Ruby.

Seven exercises: age in seconds, author age, hours in a year, minutes in a decade, a full-name greeting, a favourite-number suggestion, a table of contents.

Every one reads input with gets.chomp.to_i or .to_f, and every one silently accepts garbage. "abc".to_i is 0, so the age-in-seconds program given a typo cheerfully reports you are 0 seconds old and exits successfully. No error, no warning, no indication anything went wrong.

That is a better teaching example than most deliberate ones, because the failure is invisible rather than loud. Beginners learn to fear exceptions, and the more dangerous failure is the one producing a confident wrong answer. Ruby has Integer("abc"), which raises, and that is the version worth teaching first, strict by default, lenient once you have decided you want lenient.

There is a subtler second bug: age * 31536000 hardcodes 365 days, which over a lifetime is roughly two weeks of missing seconds.

Coming back years later, the exercises are fine and the input handling is what I would rewrite. Validating at the boundary is easier to learn at seven lines than at seven thousand.