Ruby 101: Method Definitions
Got a question or comment about this article? Find us on twitter and let us know!.
Objects manage state, and they also exhibit behavior. In this article, we'll be learning how to add behavior to classes that we write in Ruby.
By "behavior" we mean, what the class, or an instance of the class, can "do." While variables allow an object to store data, Ruby objects can define methods that execute code. This is an essential concept in object-oriented programming. Objects don't just encapsulate data, they also perform actions and can have responsibilities assigned to them.
1. The Basics
Sometimes the best way to learn is to dive right in. Take a look at this Ruby code.
|
|
This Ruby code defines our Telephone class. A class is a blueprint for how to make objects of that class. We can create a new Telephone object by calling the new method on our class:
|
|
my_phone is now an instance of a Telephone. What can our instance variable do that a plain Object can't do? Well... nothing yet. Let's teach a Telephone how to dial a phone number:
|
|
Here on line 3, we've defined an instance method by using the def keyword. Save this code into a file named phone.rb, and run it:
c:\> ruby phone.rb Dialing 1-800-555-1212...
We can define as many instance methods as we'd like. Let's teach our object to hang up the phone.
|
|
We'll get this:
c:\> ruby phone.rb Dialing 1-800-555-1212... Hung up.
There is one special instance method you should know about, called the
|
|
Let's run it again:
c:\> ruby phone.rb New telephone created! Dialing 1-800-555-1212... Hung up.
Initializers can take arguments, just like our dial method did. We pass the actual argument values when we call new to create instances of our object. If we change our initializer to this:
|
Now we are required to provide the phone's home area code when we construct a Telephone instance:
|
And now we'll get output like this:
c:\> ruby phone.rb New telephone created! Our home area code is 312. Dialing 1-800-555-1212... Hung up.
Class Methods vs. Instance Methods
Java and C#
So far we've learned how to create instance methods. They're called that because we have to first create an instance of our class before we can call them.
Sometimes we have functionality that seems appropriate to all telephones, regardless of _which_ telephone we might use. We can create class methods - methods that apply to the whole class, and not any specific instance.
Since all of our telephones have one thing in common - their manufacturer - we can create a class method to report the name of the manufacturer:
|
|
Notice how we prefix the self keyword in front of the method name to indicate that it's a class method, instead of an instance method. Let's run it:
c:\> ruby phone.rb Purple Telco
Notice how we didn't need to create any instances first. manufacturer is a class method: all we needed was the name of the class.
Congratulations! You now know the basics of instance and class methods in Ruby.
