If you ever get confused about Class Methods, Instance Methods, Class Variables and Instance Variables in Ruby, read this post and you’ll understand it better :)
Class Methods
- Class methods belong to a class in Ruby, and it can be used without instance any class object.
- The definition of class methods has a “self” prefix.
1 2 |
|
Instance Methods
- Instance methods belong to any instance of a class in Ruby. To use instance methods, you always need to have an existing instance first. Usually this means you have called
new()
method. - Instance methods do not have “self” prefix in their definition.
1 2 |
|
Class Variables
- Class variables belong to a class in Ruby. In other words, each class in Ruby automatically has an object even without any instances. The class variables are constants of the class object.
- Class variables are totally separated with instance variables (obvious though). The value of a class variable doesn’t change when the instance variables having the same name change.
- The name of a class variable has the “@@” prefix.
1 2 3 |
|
Instance Variables
- Instance variables belong to an instance of a class in Ruby.
- Different instances have their own set of instance variables.
- The name of an instance variable has the “@” prefix.
1 2 3 4 |
|
A quick demo
So now I have a quick demo to show more about the Class/Instance methods and variables.
In this demo, a Fruit class is created. The Fruit class has a class variable @@color
, and the Fruit class instances have a instance variables @color
.
Fruit class has a class method self.show_color
, and an instance method with the same name show_color
.
Now check out how these stuff works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
The test file:
1 2 3 4 5 6 7 8 9 10 |
|
Executing the test.rb
file will generate the following result:
1 2 3 4 5 6 7 |
|
Summary of the demo
-
<Class>.new
instances an object by calling theinitialize
method. Instance variables are initialized -
Instance methods only calls the instance methods within itself, even use the
self
prefix.
1 2 |
|
Both call the instance method, and shows the color: green
-
The change on instance variables doesn’t affect the class variables
-
Class methods can be called without instances
1
|
|
- Instance methods can’t be called without instances. The following statement will exceptions (NoMethodError).
1 2 3 4 |
|