As far as I understand, everything in Ruby is an object, and every object has a superclass, except BasicObject
, which is at the top of the inheritance tree.
What is the superclass of keywords like def
, begin
, and alias
?
As far as I understand, everything in Ruby is an object, and every object has a superclass, except BasicObject
, which is at the top of the inheritance tree.
What is the superclass of keywords like def
, begin
, and alias
?
They're keywords, not objects. If anything, they would be methods in
Kernel
, and have classMethod
as a result, but they're just keywords, and as such have neither class nor superclass. They're a special case and treated specially by the interpreter; they're parsed to produce the abstract syntax tree that the interpreter actually executes, and probably long gone by the time anything involving objects and classes is done. After all, how wouldend
work as a method?Note that not everything that looks like a keyword is one. Take, for example,
loop
:While it may look like a keyword, it's actually the method
Kernel#loop
.By far the easiest way to tell if something is a method or a keyword is to run this long, complicated code on it:
where
name_to_test
is either a Symbol literal or an instance of Symbol. It uses the always-available methodObject#method
, which either returns theMethod
with that name or throws aNameError
. If it operates silently -- i.e. doesn't raise any errors -- then you've got a method; if it raises an error, it's not a method. Note that it could also be a variable, not a keyword or method, but it should be easy enough to tell by looking at the previous code in the file, and a quick search through the docs.If you want to see the current list of keywords (or don't feel like booting up IRB/your favorite IDE), check this file in the RMI source. It's a little hard to understand, but basically, if you see
keyword_[thing you're looking for]
in that list (possibly with a leading_
removed), it's a keyword. To make this answer as self-contained as possible, here's the (current) list of keywords, based on that:(Many thanks to engineersmnky for pointing the list out! Never would have found it on my own.)