Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do method definitions return symbols?

Tags:

ruby

When you define a method, it returns a symbol with the same name as the method. Is there a point to this? Or is it just there as validation that you created it?

Like so:

def something
   ...
end
# => :something
like image 583
Joe Cutler Avatar asked Dec 05 '22 05:12

Joe Cutler


1 Answers

IRb always displays the result of calling inspect on the value of the last expression that was evaluated. It doesn't matter whether that expression is a literal expression, a conditional expression, a message send, a class definition expression or a method definition expression.

Everything returns a value in Ruby, i.e. everything is an expression, there is no such thing as a statement in Ruby.

In the past, the return value of a method definition expression was undefined. Most Ruby implementations simply returned nil from a method definition expression, but Rubinius for example returned the CompiledMethod object for the method that was defined.

With Ruby 2.1, the return value of a method definition expression was standardized to be the Symbol corresponding to the method's name. This allows you to use the method definition expression as an argument in methods that expect the name of a method as an argument.

Some examples:

# Before Ruby 2.0:
def foo; end
private :foo

# After Ruby 2.0:
private def foo; end # similar for `protected`, `public`, `module_function`

# Before Ruby 2.0:
def map; end
alias_method :collect, :map

# After Ruby 2.0:
alias_method :collect, def map; end

On a personal note, I would have preferred a method definition expression to evaluate to an UnboundMethod object corresponding to that method, and methods like public, private, protected, alias_method, module_function etc. should be amended to accept UnboundMethods in addition to Symbols and Strings.

like image 51
Jörg W Mittag Avatar answered Feb 24 '23 01:02

Jörg W Mittag