Class methods are methods we can call directly on the class itself, without having to instantiate any objects.
This can be useful when there is no logical need to create an object of the class, such as when a class is used to group similar methods and functionality (like mathematical operations).
One example is a Math class that includes a square method for returning the square of its parameter. There is no logical need to create an object of the Math class just to call the method. This is where class methods come into play.
Class methods are defined using the self keyword:
puts “A Person”
Now, the method is a class method and can be called directly from the class, without the need of an object:
# outputs “A Person”
Class variables are accessible to every object of a class. A class variable belongs to the class, not the objects.
You declare a class variable using two @ signs, for example @@name.
We can, for example, keep count of all Person objects created using a class variable:
@@count = 0
@@count += 1
p1 = Person.new
p2 = Person.new
# outputs 2
In the code above, @@count is a class variable. Since the initialize method is called for every object that is created, incrementing the @@count variable will keep track of the number of objects created.
We also defined a class method called get_count to return the value of the class variable.
In the code above, we have created two objects of the Person class so the value of the @@count variable is 2.
A class can also contain constants. Remember, constant variables do not change their value and start with a capital letter. It is common to have uppercase names for constants, as in:
PI = 3.14
You can access constants using the class name, followed by two colon symbols (::) and the constant name, for example:
# outputs 3.14
CLICK ON THE BUTTON BELOW TO GO TO THE RUBY MAIN COURSE PAGE.
© License: All Rights Reserved
CONTACT HOLLA TECH – LEARN SUPPORT