Who Is This “self” Anyway?
We've been talking about self as the top-level object; depending on your turn of mind, you might be identifying it with the script, or with yourself as the programmer. But strictly speaking, self is not really one object, but shorthand for the “current object,” which is whatever object is in control at any given moment. In a simple script with no defined objects, self is always main, the top-level object, but when other objects exist, they refer to themselves when saying self. After all, this is just how we use the word in ordinary language.
#!/usr/bin/env ruby print "top-level object identifies itself as " p self an_object = Object.new def an_object.identify_yourself p self end print "an_object identifies itself as ...
Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.