Patrick Doyle wrote:
> Well, there is one difference -- the last one returns a different value 
> for B.

Remember that (1) classes are also objects in Ruby and (2) every object 
in Ruby has its own singleton class (also known as "meta class" and 
"eigen class").  An object's singleton class is like a human's 
personality -- each personality is unique to the particular human.

When you write:

  def my_object.my_method
   ...
  end

you are using a shortcut for:

  class << my_object
    # we are inside my_object's singleton class! :-)


    def my_method
      ...
    end
  end

Thus, you are adding a my_method to the personality of my_object.

> I'm not sure what that buys you, but it's the thing that dumbfounds 
> me the most about this issue.

It buys a lot.  Imagine you are writing a super hero simulation game 
where objects are randomly given super powers.  How would you do this?

In Java, the typical approach is to make a class heirarchy:

  class Human {}
  class Hero extends Human {}
  class SuperHero extends Hero {}

  Human h = rand(2) == 1 ? new SuperHero() : new Human();

and randomly instantiate the particular SuperHero class.

In Ruby, we can do something better and give super powers directly to a 
particular object:

  class Human; end

  h = Human.new

  if rand(2) == 1
    def fly!
      puts "you soar like an eagle!"
    end

    def hide!
      puts "you became invisible!"
    end
  end

Understand now?
-- 
Posted via http://www.ruby-forum.com/.