How to find the + class in Ruby


The design philosophy of ruby is just amazing. So I did 1 + 2 and got 3. I managed to make this: 1.+(2) # => 3.

As cool as this was, I also wanted to test out the class method on the + method.

=> SyntaxError: (irb):14: syntax error, unexpected '.'

And then:

=> NoMethodError: undefined method `[email protected]' for NilClass:Class


NoMethodError: undefined method `[email protected]' for Fixnum:Class

Why was +(2).class a fixnum and not an integer? I try it again with +(2.to_i).class and the same error appears for +(2).class.

But back to the key question: How do I find the class of the + method?

1 + 2 is calling the + method on 1 with 2 as an argument, which is the same as 1.+(2).

However, because of precedence, +(2).class is actually calling (2).class first, returning an instance of Class, then calling the nonexistent [email protected] method, which is the unary plus method that only exists for Numeric. You can test this by typing (+(2)).class, which returns Fixnum as one would expect. This is also the source of the error for +().class, because () returns nil, and the class of nil is NilClass, which also doesn't have a [email protected] method.

tl;dr: because precedence made the leading + evaluate last, as [email protected].

The + method on any object is of the class Method, as is any other method on any object. However, typing + calls the method instead of returning it, because Matz saw in a dream that a programming language that returns methods instead of calling them doesn't run. You can have the method returned to you by calling the method method with the method name, like so: 1.method(:+). Then you can make the method object tell you what its class is: 1.method(:+).class.