Ruby - Using Singleton Methods

Description

Using Singleton Methods

Demo

class Creature 
   def initialize( aSpeech ) 
      @speech = aSpeech #   w w w.  j  a va2 s .c  om
   end 

   def talk 
      puts( @speech ) 
   end 
end 
mySelf = Creature.new( "growl" ) 
def mySelf.howl 
    if FULLMOON then 
      puts( "How-oo-oo-oo-oo!" ) 
   else 
      talk 
   end 
end 

cat = Creature.new( "miaow" ) 
dog = Creature.new( "woof" )

Here, even though mySelf.howl method has been declared outside the Creature class, it can call the instance method talk.

That's because the howl method now lives "inside" the mySelf object so has the same scope within that object as the talk method.

It does not, however, live inside any of the mySelf's fellow creatures.

The howl method belongs to him and him alone.

Related Topic