furqan furqan - 1 year ago 50
Ruby Question

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

As far as I understand, everything in Ruby is an object, and every object has a superclass, except

, which is at the top of the inheritance tree.

What is the superclass of keywords like
, and

Answer Source

They're keywords, not classes. If anything, they would be methods in Kernel, as opposed to classes with superclass BasicObject, but they're just keywords, and as such have neither class nor superclass. They're a special case and treated specially by the interpreter.

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

loop do
  puts 'Hello, world!'

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 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, but it should be easy enough to tell.

If you want to see the current list of keywords (or don't feel like booting up IRB/your favorite IDE), check this file (CTRL+F keyword_) in the RMI source. It's a little hard to understand, but basically, if you see keyword_[thing you're checking] in that list, 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 it out! Never would have found it on my own.)