Gavin Kistner
10/27/2006 4:17:00 PM
bparanj@gmail.com wrote:
> What is the purpose of singleton method? Why is singleton method
> defined on individual object instead of a class? TIA
class Person
def initialize( name )
@name = name
end
def do_the_hustle
puts %Q|#@name says, "doop dee doop de doop dee doop doo ..."|
end
def electric_slide
puts %Q|#@name says, "It's electric!"|
end
def dance
do_the_hustle
end
end
bob = Person.new( "Bob" )
jim = Person.new( "Jim" )
janice = Person.new( "Janice" )
def janice.dance
electric_slide
end
crowd = [ bob, jim, janice ]
crowd.each{ |person|
person.dance
}
#=> Bob says, "doop dee doop de doop dee doop doo ..."
#=> Jim says, "doop dee doop de doop dee doop doo ..."
#=> Janice says, "It's electric!"
With singleton methods, you can change the way a single object responds
to an event (or add unique functionality) without having to create a
whole new subclass just for that object.