Posts tagged ‘class method’
class methods
What is a class method ?
- A class method resides at the class level.
- An instance method resides at the object level.
Class level – basically means such methods are associted with class, rather than being with object directly.
How can we define such class methods?
In there ways:
- Using classname.classmethod_name
- Using self.classmethod_name
- Defined your method as
Refer : Sector #1
How can we call such methods?
Classname.classmethod_name
Note:
> You can use the self variable, which is always pointing to the current object
> For creating the anonymous class(class having no name), we use the << notation.
Refer : Sector #2
How to access a class method from an instance (using object) ?
<instance_name>.class.<class_method_name>
Refer : Sector #3
# ======= Sector #1 ===============
class << self
def classmethod_name
# something here
end
end
# ======= Sector #2 ===============
class Myclass
def Myclass.class_method1
p “Its a class method using class name”
end
def self.class_method2
p “Its another class method using self”
end
class << self
def class_method3
p “This too using class self”
end
end
end
Myclass.class_method1
Myclass.class_method2
Myclass.class_method3
o/p
# “Its a class method using class name”
# “Its another class method using self”
# “This too using class self”
# ======= Sector #3 ===============
class Myclass
def Myclass.class_method
p “Called using an instance of Myclass i.e obj”
end
end
obj = Myclass.new
obj.class.class_method
o/p
Called using an instance of Myclass i.e obj


