Object Oriented Design (OOP)
OOP is about structuring your program like physical objects. Interestingly, everything in #Ruby is an object. But what is an object? You have things called classes, like "box" or "user", that act like a noun. You have variables, like "size", "weight", "length", or "status", that describe the object similar to adjectives. And you have methods, like "destroy", "calculate", "open", or "new", that act like verbs the object can perform.
Lets look at a class now that contains these concepts:
class Firearm
def initialize
@ammo = 10
end
def ammo
@ammo
end
def shoot
puts "Bang!"
@ammo -= 1
end
end
Now I create one of these objects using #new and see how I can interact with it.
First, I make a variable to represent this particular instance, or version, of our Firearm.
irb(main):001:0>glock_27 = Firearm.new => #
Now I use #ammo to check our ammunition
irb(main):002:0>glock_27.ammo => 10
And here I #shoot which reduces our ammunition by 1.
irb(main):003:0>glock_27.shoot
"Bang!"
=>9
The #new method I called created a single, stand-alone instance of our Firearm class. The instance has its on identity. The class acts as template for the instance. I could continue calling the #new method and create as many instances as we need. The ammo and shoot methods return messages containing instance-specific information. #Ammo checks that variable for us while #shoot reduces that variable by 1 and then returns it as well.
Now, I know one of you out there may be saying, "thats nice but a Glock 27 has a standard nine round capacity..." Oh, well of course. To change ammo inside an instance, I'll need a method to set the instance variable "@ammo".
def Firearm
...
def ammo=(ammo)
@ammo = ammo
end
end
Again, it looks a little odd having ammo written 4 times in one method. The 'ammo' in the parentheses is called an argument. It could have been represented by any word, but I chose 'ammo' because it accurately describes what information I'm giving the method. The method will use whatever I pass to it to set @ammo. Now I can use it like so:
irb(main):001:0>glock_27.ammo=14
=>14
irb(main):002:0>glock_27.ammo=9
=>9
And broken down for brevity:
irb(main):001:0>glock_27(our class)
.ammo= (our method)
20 (our argument)
=>20 (The new @ammo value returned to us)
So now I have a method that can set our ammo variable. This is refered to as a 'setter' method. Its counter-part, a 'getter' method, is the #ammo method we already previously made.
So what conclusions can I draw from all this?
- A class is a template for creating objects.
- A method is a request for an action or message.
- A variable is a placeholder for specific data.
- An instance variable is a placeholder for its own instance of a class.