Classes are what considered to be the blueprint that determines how an object should be built, the object being built by the class is called an instance.
.new is a built-in method that is used to instantiate a new object with the same characteristics of the class, besides the .new method, we can define other methods inside the class that determines the behavior of the instance created by the class.
Notice that any variables defined within a method can NOT be shared with other methods inside the class, it is only accessible within the scope of the method that the variable was defined within but there is a solution for that, the solution would be by creating an instance variable which can be accessible from within any method in the class, the way we can create an instance variable is by adding the symbol @ before the variable name, for Example: @name instead of name
Besides the instance variables, we also can create class variables, class variables are what considered to be global variables, here is an example of when we can use class variables:
let's say we have a User class and we wanted to keep track of the count of the user instances created by the User class:
class User
@@count = 0
def initialize
@@count += 1
end
end
Having a class variable defined within the class will keep track of all the instances that has been created and we can simply add a method that returns that count value.
Top comments (0)