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:

  1. Using classname.classmethod_name
  2. Using self.classmethod_name
  3. 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

March 22, 2008 at 6:15 am Leave a comment


Categories

posts[:recent]

@@name = PRAYAS

This blog has more intention for my self reference@24×7. But if some search engine crawler directs you to my page, believe I may learn form your comments or feedback. Hence feel free to comment good or bad!
prayas2010@gmail.com

visitors[:since_Mar'08]

free web counter

Prayas@Nikon

A colored life

Chhweet Kidss

An independent world

More Photos

Feeds


Follow

Get every new post delivered to your Inbox.