From: "Jesús Gabriel y Galán" Date: 2009-12-15T00:17:04+09:00 Subject: Re: about class and module On Mon, Dec 14, 2009 at 3:10 PM, Ruby Newbee wrote: > On Mon, Dec 14, 2009 at 9:37 PM, Brian Candler wrote: > >> >> In addition: Objects have singleton classes, which are private to that >> object. You can use 'extend' to add a module to an individual object's >> singleton class. >> >> module Foo >>  def greet >>    puts "Hello, #{self}!" >>  end >> end >> s = "you" >> s.extend Foo >> s.greet         # => "Hello, you!" >> >> Note we have not touched class String at this point. >> >> But since classes are objects too, the same applies to classes. You can >> use a module to add "class methods" to a class. >> >> String.extend Foo >> String.greet    # => "Hello, String!" >> > > Thanks for the points. That looks very interesting. > As you said "Objects have singleton classes", what's "singleton > class"? could you show a description by examples? > I never saw that before. Thanks again. A singleton class of an object (also referred sometimes as eigenclass or metaclass, although there has been much debate about which term to use), is a special class that can be attached to each object to specify per-object behaviour. This means, a place where you put methods that can only be called on a specific instance. Brian already gave you an example by means of extending an object with a module. Here are some other examples: irb(main):001:0> s = "hello" => "hello" irb(main):006:0> def s.to_upper_case irb(main):007:1> self.upcase irb(main):008:1> end => nil irb(main):009:0> s.to_upper_case => "HELLO" As you can see we define a method for s, and only s, this is the only object which will have the method to_upper_case. No other string will have it. As Brian pointed out, you can extend a single object with a module, and what this does is add the module's methods to the singleton class of the object: irb(main):010:0> module Testing irb(main):011:1> def test irb(main):012:2> "what a test !" irb(main):013:2> end irb(main):014:1> end => nil irb(main):015:0> s.extend Testing => "hello" irb(main):016:0> s.test => "what a test !" (s is the previous string). This strategy is a really good way to add functionality to object, since you don't mess with core classes (which can break things), but only act on the specific objects you want to modify. In Ruby, classes are objects too (they are instances of the Class class): irb(main):017:0> String.class => Class This means that they also have a singleton class where to place methods that can only be called on that specific object. As the object is a class, they are usually called class methods, but they are not really different to singleton methods on any object: irb(main):018:0> def String.test irb(main):019:1> "testing again" irb(main):020:1> end => nil irb(main):021:0> String.test => "testing again" Hope this helps, Jesus.