March 2009
Intermediate to advanced
194 pages
4h
English
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 ...