Ruby tutorial session 8

Singleton Classes and Methods:

Hi Readers,

In this post/page we are going to learn about singleton classes and their methods.

Example:

    require 'person' 
     
    # Every object has two classes: the class of which it is an instance, 
    # and a singleton class. 
    # Methods of the singleton class are called singleton methods 
    # and can only be invoked on that particular object. 
    andreas = Person.new("Andreas") 
    def andreas.andreas_says_hi 
      "Andreas says hi" 
    end 
    andreas.andreas_says_hi 
     
    # Class methods are singleton methods on the class 
    # object and can be defined like this: 
    def Person.count 
      @@count ||= 0 
    end 
    puts Person.count 


In our previous sessions example person class requiring in this, and we are defining a method with the class instance. So here Person in singleton class.

Just go through this example and practice it.

If you like follow the blog.

Thank you.

No comments:

Post a Comment

My Experience in RUBYCONF INDIA 2016

Hi Readers, Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 ma...