Ruby - Using Singleton Methods

Description

Using Singleton Methods

Demo

class Creature 
   def initialize( aSpeech ) 
      @speech = aSpeech # from ww  w.j  a va  2s  .  com
   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