Feature #7998

"def" should return a value (the symbol of the method name) instead of nil

Added by Peter Marreck about 1 year ago. Updated about 1 year ago.

[ruby-core:53086]
Status:Open
Priority:Normal
Assignee:-
Category:-
Target version:next minor

Description

The C code that implements Ruby method definitions already creates a symbol corresponding to the method name.

I propose that the "def... end" block returns this symbol.

This would allow the following elegant Ruby code:

protected def foo(); end

private def bar(); end

since "protected" and "private" already take symbol arguments.

I estimate that this would be extremely easy to implement while creating extremely minimal existing code impact.

I proposed this idea to the #ruby IRC channel on freenode.net and it was received very well, they encouraged me to file this ticket! Thank you for considering.

History

#1 Updated by Nathan Zook about 1 year ago

+1

While the proposed usage is good, I immediately thought about this:

newmethname = moduleeval <<-RUBY
def prefix
#{val}_postfix
...
end
RUBY

#2 Updated by Thomas Sawyer about 1 year ago

=begin
It has been suggested long long ago. Probably more than once. Here is a link to one: #3753.

Once we start looking at code like that for a while will we then start to think, why not just:

public foo()
  ...
end

protected foo()
  ...
end

private bar()
  ...
end

=end

#3 Updated by Guoliang Cao about 1 year ago

This is a nice addition indeed and I remember I asked for it too in the
past. One usage could be method annotation like what is done in some
command line library:

desc 'Do something'
def do_something
...
end

The above code looks nice but I believe its underlying code involves
using methodadded and is fragile when methodadded is also used for
other functionalities.

If def returns method name, then a comma is all we need to remove the
meta-programming complexity.

desc 'Do something',
def do_something
...
end

I really wish one day this will be added to Ruby.

#4 Updated by George Koehler about 1 year ago

=begin
I have a problem with this feature.

module Frog
private def self.sound
"Ribbit!"
end
end

With this feature, def..end would return :sound, then private :sound would set Frog#sound to private. This is wrong. I defined Frog::sound, not Frog#sound. Surprise! There is no way for private :sound to know that I defined a metamethod, not an instance method; because def..end only returned a Symbol, not the whole definition. With this feature, "private def" only works for instance methods, not for metamethods.
=end

Also available in: Atom PDF