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 this with any method in any class, even the built-in methods. If you don’t like the reverse method for strings, you can just redefine it in much the same way, but I don’t recommend it! It’s best to leave the old methods alone and to make new ones when you want to do something new.
Confused yet? Let me go over that last program some more. So far, whenever we executed any code or defined any methods, we did it in the default “program” object. In our last program, we left that object for the first time and hopped into the Integer class. We defined a method there (which makes it an integer method), and now all integers can use it. Inside that method we use self to refer to the object (the integer) using the method.
3.144.109.75