[#1816] Ruby 1.5.3 under Tru64 (Alpha)? — Clemens Hintze <clemens.hintze@...>

Hi all,

17 messages 2000/03/14

[#1989] English Ruby/Gtk Tutorial? — schneik@...

18 messages 2000/03/17

[#2241] setter() for local variables — ts <decoux@...>

18 messages 2000/03/29

[ruby-talk:02278] Re: Adding method to Object -- Why doesn't this work?

From: Dave Thomas <Dave@...>
Date: 2000-03-30 19:58:53 UTC
List: ruby-talk #2278
h.fulton@att.net writes:

> I'm a little in the dark about singleton methods. I'm 
> not sure when one would use one instead of an instance
> method.

A there are two kinds of singleton method. (Actually there aren't,
there's only one, but it's less brain warping to divide them into two
groups)

A singleton method of a class is defined as

  class Fred
    def Fred.sayHi
       puts "Hello"
    end
  end

or as

  class Fred
    # ..
  end
  def Fred.sayHi
     puts "Hello"
  end


The thing that's special about these is that they can be called
without an object instance -- the receive is the class, not an
object. So, you could say

  Fred.sayHi

Not an instance of Fred in sight.

In the book, we call these class methods.


The other kind of singleton method is when you add a method to an
object:

  class Bert
    def hello
      puts "hello"
    end
  end
  obj = Bert.new
  def obj.goodbye
    puts "goodbye"
  end
  obj.hello
  obj.goodbye

  another = Bert.new
  another.hello
  another.goodbye

Which produces:

  hello
  goodbye
  hello
  -:15: undefined method `goodbye' for #<Bert:0x4018b2ec> (NameError)


And that's that.

Except... why did I say there's only one kind of singleton method?

Well, when you say

  def Fred.sayHi
  end

You're simply adding a method to the object referenced by Fred. Fred
is a constant which references an object of class Class, which
contains the definition of class Fred. (Confused? I know I am). So, in 
fact the two kinds of definition are the same.


> I had actually thought it might be hours till I got an
> answer... most of the people on this list are asleep right now,
> aren't they?

I know I am.


Dave

In This Thread

Prev Next