Why are methods in Ruby documentation preceded by a hash sign?
I just realized that none of the other answers touch the most trivial aspect of the question: why the #
sign?
I have two theories:
- 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 likeArray >> #new.
(The>>
is itself a method that returns the method passed to it. So, in Ruby that would beArray.method :new
.) In Smalltalk documentation, methods are generally referred to asClass>>method
, but in RubyClass:method
would have made more sense, except that it is easily confused withClass::method
. Therefore,Class#method
was chosen. - 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?
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.
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.