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?

asked May 30, 2012 at 10:51

1 Answer 1

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
answered May 30, 2012 at 11:19
2
  • 5
    ... functions can have side-effects. They're called impure functions. Commented May 30, 2012 at 12:04
  • 1
    Thanks, very enlightening. I should have used the word sub-routine instead of function, I understand this was misleading. Commented May 30, 2012 at 14:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.