Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata