Feature #10183
open
An alternative name for method `class`
Added by sawa (Tsuyoshi Sawada) over 10 years ago.
Updated about 7 years ago.
Description
The method class
is special in that it always has to have an explicit receiver in order to avoid crash with the keyword class
. But this is very inconvenient. I have seen so many
self.class
in codes. I propose that there should be an alternative name for this method so that it can be used with an implicit receiver, and the method name class
should be gradually depricated.
As for the name, I have no clear idea. I can only think of klass
, but perhaps someone else might come up with a better name.
The problem with object_class is that it is longer than self.class
Remember that object_id used to be called id in the past before that was renamed.
Came here to make a similar feature suggestion. Ideally class
would be aliased as something such as klass
which has become somewhat of a ruby idiom to avoid collision with the class
keyword. Though I'd also be interested to discuss the possibility of introducing shorter syntax for self.
, such as some kind of single-character prefix. Some examples:
self.class::MYCONST
klass::MYCONST # alias of #class method
$class::MYCONST # special reserved global variable
~class::MYCONST # tilda prefix shouldn't clash with any existing syntax rules
My guess is that self.class mostly appears in the context of metaprogramming. Metaprogramming is already not as concise as plain programs anyway, so the self.class
may not be that much of an issue. Using class
in general code should be avoided anyway, and replaced with resopnd_to?
,...
Also, with something like klass
, all Ruby users would have to learn this special case.
My guess is that self.class mostly appears in the context of metaprogramming.
Why? In simple inheritance, you may have cases like:
self.class::CONST # the constant is redefined in subclasses
def clone_with_tricks(...)
self.class.new(...) # produce exactly the same class as self
end
...and a lot of others.
BTW, I'd rather have some special syntax for generic case "want to use local name, but it is keyword". For example (syntax is bad, but shows usage):
def my_method(if:, retry: false)
if %if.call # `if` variable from local context, not `if` keyword
....
%class # locally-available `class` method, not `class` keyword
return false unless %retry
end
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0Like0