What is the class of keywords like def, alias, and begin in Ruby, if any?

221 views Asked by At

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?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

They're keywords, not objects. If anything, they would be methods in Kernel, and have class Method 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 would end work as a method?

Note that not everything that looks like a keyword is one. Take, for example, loop:

loop do
  puts 'Hello, world!'
end

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:

method(name_to_test)

where name_to_test is either a Symbol literal or an instance of Symbol. It uses the always-available method Object#method, which either returns the Method with that name or throws a NameError. 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:

__LINE__, __FILE__, __ENCODING__, BEGIN, END, alias, and, begin, break, case, class, def, defined, do, else, elsif, end, ensure, false, for, in, module, next, nil, not, or, redo, rescue, retry, return, self, super, then, true, undef, when, yield, if, unless, while, until

(Many thanks to engineersmnky for pointing the list out! Never would have found it on my own.)