Python to Ruby: Two puzzlements...

G

Glenn Vanderburg

(There've been a lot of good replies to this, but I'll try to tie it
all together a bit.)

I guess I'm just surprised by the implicit reference. In Python
(and Perl, to an even greater if more obscure degree) extensions like
that are quite explicit.
and

For what it's worth, this is making some *very* cobwebbed
portions of my brain think, "Y'know, this looks like ObjC (circa 1996,
via Webobjects) on drugs."

Those two observations are related. Python and Perl both require
explicit reference to an object when calling methods, but that makes
them quite unusual as object-oriented languages go. Ruby and
Objective C are both more in the Smalltalk tradition, where *every*
call represents a method on some object or another, and if you don't
specify it explicitly, "self" is used. (In that one respect, C++,
Java, and C# also are more in the Smalltalk tradition.)

So within a method, "self" is the receiver (the object the method was
called upon) and method calls without a specific receiver also go to
the same object.

Every class ultimately extends Object, which includes the module
Kernel, so the methods defined in Object and Kernel are available
everywhere within Ruby. (Unless you take explicit measures to remove
them from certain contexts.)

At the top level, the implicit receiver is an otherwise
undistinguished instance of Object, which is why methods like "puts"
are available outside any other context.

Classes are themselves objects -- instances of Class (which itself
extends Module). Within a class definition, but outside a method
definition, "self" is bound to the class being defined. That's why
"def self.append_features" defines a class method rather than an
instance method. You'll see attributes defined with constructs like
attr, attr_reader, attr_writer, and attr_accessor: those are private
methods defined in Module, and since the class is an instance of
Module, you can call those methods on the class. You'll also
occasionally see something like this:

class Something
class <<self # what's this?
def meth1
# ...
end
def meth2
# ...
end
end
end

"class <<self" opens a context in which method definitions define
class methods. So the above is basically the same as this:

class Something
def self.meth1
# ...
end
def self.meth2
# ...
end
end

The second version is, to my mind, much clearer to the beginner.

(Oh, and one more thing: I suspect even _why would admit that the
code he highlights on RedHanded is rarely ideal for newcomers to
Ruby. :)

---Glenn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,967
Members
47,519
Latest member
OtisLucket

Latest Threads

Top