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 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.
- 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
- Instance methods do not have “self” prefix in their definition.
- 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 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
Fruit class has a class method
self.show_color, and an instance method with the same name
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
test.rb file will generate the following result:
1 2 3 4 5 6 7
Summary of the demo
<Class>.newinstances an object by calling the
initializemethod. Instance variables are initialized
Instance methods only calls the instance methods within itself, even use the
Both call the instance method, and shows the
The change on instance variables doesn’t affect the class variables
Class methods can be called without instances
- Instance methods can’t be called without instances. The following statement will exceptions (NoMethodError).
1 2 3 4