Could anyone explain what exactly we meant by a Singleton Method ?
See if i am thinking it right....
class A
end
a = A.new
a.instance_eval <<-EOS
def wishing_hello
puts "HELLO !!"
end
EOS
so, here wishing_hello will be a singleton method ?
Yes. A singleton method is basically a method that belongs to one
object only. Since methods actually "belong to" classes and modules,
rather than objects in general, Ruby implements singleton methods by
means of singleton classes. Each object has its own, dedicated class
-- its singleton class -- where its singleton methods are stored.
You can gain direct access to an object's singleton class like this:
class << a # from your example
def wishing_goodbye
puts "GOODBYE!!"
end
end
wishing_goodbye is now defined as an instance method in the singleton
class of a.
On 11/11/06, dblack@wobblini.net <dblack@wobblini.net> wrote:
Hi --
On Sat, 11 Nov 2006, sur max wrote:
> Could anyone explain what exactly we meant by a Singleton Method ?
> See if i am thinking it right....
>
> class A
> end
> a = A.new
> a.instance_eval <<-EOS
> def wishing_hello
> puts "HELLO !!"
> end
> EOS
>
> so, here wishing_hello will be a singleton method ?
Yes. A singleton method is basically a method that belongs to one
object only. Since methods actually "belong to" classes and modules,
rather than objects in general, Ruby implements singleton methods by
means of singleton classes. Each object has its own, dedicated class
-- its singleton class -- where its singleton methods are stored.
You can gain direct access to an object's singleton class like this:
class << a # from your example
def wishing_goodbye
puts "GOODBYE!!"
end
end
wishing_goodbye is now defined as an instance method in the singleton
class of a.