On Sun, 28 May 2006, Paul D. Kraus wrote:
Perl has me all turned around with ruby classes.
I see some classes use a ‘self.’ and others don’t. When to use?
‘self’ is the default object, a role that rotates among different
objects at different points in your program. When, and even whether,
you use it explicitly depends on what you’re trying to do.
If you want to add a singleton method (i.e., a method for one specific
object) to the object that is self, you would do:
That construct is very commonly used for creating class methods:
but you can do it with any object, and in fact it’s just a
not-very-special case of:
which is how you would add a singleton method to some_object.
Since self is the default object, when you call a method, you normally
don’t have to specify self as the receiver:
x # effectively the same as: self.x
However, when you use methods that end with = (equal sign), you do
have to use an explicit ‘self’ receiver, to distinguish the method
call from a local variable assignment. This is the (small) price paid
for the nice syntactic sugar that comes with =-terminated methods:
@x = n
self.x = 10 # calls method x= with argument 10
x = 10 # sets local variable x
Also what does an @ do in front of a variable?
@variable is an instance variable. Whenever you see @variable, you’re
seeing an instance variable that belongs to whatever object is ‘self’
at that moment.
I think i understand private methods basically they are things only used
with in the class and never return a value or effect anything beyond that
No; the difference between a private method and a public method is
that a private method cannot be called with an explicit receiver. You
cannot do this:
c = C.new
if z is a private instance method of c. That means that you can only
do the equivalent of c.z under circumstances where ‘self’ is c –
because, under such circumstances, a simple call to z will be
equivalent to c.z (as in the earlier example). So generally you only
see calls to private methods inside other methods in the same class:
x # OK, because no explicit receiver; it uses self
(There are a couple of special cases etc. but that’s the bulk of it.)