From: Brian Candler Date: 2009-12-15T00:05:14+09:00 Subject: Re: about class and module Ruby Newbee wrote: > As you said "Objects have singleton classes", what's "singleton > class"? could you show a description by examples? s1 = "a string" s2 = "another string" def s1.wibble puts "bibble" end s1.wibble # => "bibble" s2.wibble # => NoMethodError: undefined method `wibble' Every object has a 'singleton class' which contains methods private to that object. A class, like class Foo, is an instance of class Class. So the 'class methods' of Foo are just methods in the singleton class of Foo. class Foo; end def Foo.wibble puts "I am a singleton method" end Foo.wibble Another way to add methods into the singleton class is like this: s1 = "hello" class << s1 def hey; puts "hey!"; end end s1.hey So of course this works for classes (and class methods) too: class Foo class << self def bar puts "In bar" end end end Foo.bar The singleton class is itself an object. It's quite hard to grab hold of, but the above gives you a clue to the trick: s = "hello" sc = class << s; self; end So sometimes you will see code like this: class << s; self; end.class_eval { define_method(:bar) { puts "bar!" } } An object with a singleton class loses it when it is dup'd (otherwise it wouldn't be a singleton any more :-) a = "hello" def a.world; puts "world"; end b = a.dup a.world # "world" b.world # NoMethodError: undefined method `world' -- Posted via http://www.ruby-forum.com/.