7

I'm trying to understand how the puts function fits in Ruby's "Everything is an object" stance.

Is puts is the method of a somehow hidden class/object? Or is it a free-floating method, with no underlying object?

gyin
  • 185

1 Answers1

14

I'm trying to understand how the puts function fits in Ruby's "Everything is an object" stance.

First off, puts is not a function. It's sole purpose is to have a side-effect (printing something to the console), whereas functions cannot have side-effects … that's the definition of "function", after all.

Ruby doesn't have functions. It only has methods. Thus, puts is a method.

Is puts is the method of a somehow hidden class/object?

No, it's just a boring old instance method of a boring old class. (Well, a boring old instance method of a boring old mixin, actually, but a mixin is just a class which abstracts over its superclass.)

Kernel is mixed into Object, which is the (default) superclass of all objects (modulo BasicObject, of course), thus, Kernel is a common superclass (or "supermixin", if you prefer) of (almost) all objects in Ruby.

Or is it a free-floating method, with no underlying object?

There is no such thing. A method is always associated with an object (the receiver of the message), that's what makes it a "method". (At least in OO parlance. In ADT-oriented languages, the word "method" means something slightly different.)

By the way, the easiest option is always to just ask Ruby herself:

method(:puts).owner
# => Kernel
Jörg W Mittag
  • 103,514
  • 5
    ... functions can have side-effects. They're called impure functions. – amara May 30 '12 at 12:04
  • 1
    Thanks, very enlightening. I should have used the word sub-routine instead of function, I understand this was misleading. – gyin May 30 '12 at 14:49