Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Singleton methods in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 421
    Comment on it

    A regular instance method can be used by all the instances of that class and all of them will inherit their behavior from its class. But what if we want a particular instance to have a specific behavior that no other instance can have that is where singleton method is being used.Singleton methods are the methods that can only be accessible to a single object only.
    In some language this can be done by defining another class, which can only be instantiated once, but in ruby we use singleton method for that.

    For example:

    class Welcome
      def greet_user
        puts "Hello all"
      end
    end
    
    user1 = Welcome.new
    user1.greet_user
    user2 = Welcome.new
    user2.greet_user
       
    p user1
    p user2

    This will print:

    Hello all
    Hello all

    Now we want instance user1 to have a specific behavior, for that we define a method that can be accessible to user1 only

    For example:

    class Welcome
    
    end
    
    user1 = Welcome.new
    user2 = Welcome.new
    
    def user1.greet_user
    
      puts "Hello admin"
    
    end
    
    p user1.greet_user
    p user1.respond_to?(:greet_user)
    p user2.respond_to?(:greet_user)
    p user2.greet_user
    
    


    The output will be:

    Hello admin
    true
    false
    undefined method `greet_user' for #<Welcome:0x00000002f67348>

    Here respond_to? method is used to check whether the object can respond to the given method or not

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: