tags:

views:

613

answers:

5

This is something that has been bugging me for a while. When you see any ruby method printed in text, it usually appears as

Class#method

or

#method

Now, I would use

Class.method

Why are all ruby methods preceded by a pound sign? Is there any reason for it? Just curious.

+10  A: 

Note that the convention is:

Class#method

rather than

object#method

In code you would have object.method, if object was an instance of class. The # convention is not used in code.

From the RDoc documentation:

Use :: for describing class methods, # for describing instance methods, and use . for example code.

Simon Nickerson
Yes, sorry, Class#Method. Thanks.
Ed Swangren
I know that # is not used in code, but why is it used at all?
Ed Swangren
+5  A: 

From the rdoc docs:

Names of classes, source files, and any method names containing an underscore or preceded by a hash character are automatically hyperlinked from comment text to their description.

(Emphasis added.)

Sarah Mei
This doesn't answer the question.
Horace Loeb
The question is why is the # sign used. The answer is so that rdoc will add appropriate links. If you have another answer, please add it.
Sarah Mei
+1  A: 

All the answers above you list are correct. The one thing I would add is that the documentation style you said you would perfer

Class.method

would be easily confused with class methods. Since you can call class methods in ruby using the above syntax:

class Foo
  def self.say_hi
    puts "hi"
  end
end

Foo.say_hi    # => prints "hi"
delwaterman
+3  A: 

The # notation is used to refer to the canonical instance method, like String#upcase. The . notation is used to refer to the method of a particular instance, like mystring.upcase. The distinction is made to not imply that a class method 'upcase' exists.

dbarker
+2  A: 

I just realized that none of the other answers touch the most trivial aspect of the question: why the # sign?

I have two theories:

  1. It might come from Smalltalk, where symbols are written #sym (instead of :sym) as they are in Ruby. So, if you want to refer to a Method object (as opposed to calling a method), then you would call something like Array >> #new. (The >> is itself a method that returns the method passed to it. So, in Ruby that would be Array.method :new.) In Smalltalk documentation, methods are generally referred to as Class>>method, but in Ruby Class:method would have made more sense, except that it is easily confused with Class::method. Therefore, Class#method was chosen.
  2. My other theory is that it simply was chosen because # is the comment character in Ruby.

A definitive answer can only be given by whoever invented that convention. If it was invented for the Programming Ruby book, that would be either Dave Thomas or Andy Hunt, but I kind of doubt that. The book came out in 2001, Ruby started in 1993, how were they referring to methods before then?

Jörg W Mittag