Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 8 down vote accepted

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
share|improve this answer
4  
... functions can have side-effects. They're called impure functions. –  naiad 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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.