Chapter 13Creating New Classes, Changing Existing Ones

Back here, we wrote a method to give the English phrase for a given integer. It wasn’t an integer method, though; it was just a generic “program” method. Wouldn’t it be nice if you could write something like 22.to_eng instead of english_number 22? Here’s how:

class​ Integer
def​ to_eng
if​ self == 5
english = ​'five'
else
english = ​'forty-two'
end
english
end
end
# I'd better test on a couple of numbers...
puts 5.to_eng
puts 42.to_eng
five
forty-two

Well, I tested it; it seems to work.

We defined an integer method by jumping into the Integer class, defining the method there, and jumping back out. Now all integers have this (somewhat incomplete) method. In fact, you can do ...

Get Learn to Program, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.