Understading `self` in Ruby

来源:转载

Today I'd like to talk about self. If you've been programming Ruby for a while, you've likely internalized the idea of self. Whenever you read or write a program, selfis there in the back of your mind.

But for less-experienced Rubyists, selfcan be baffling. It's always changing, but it's never explicitly shown in the code. You're just expected to know.

A lot of the problems beginners face are caused by not understanding self. If you've ever "lost" an instance variable or puzzled over what data is visible to a mixin, then it's because you didn't understand selfin that context.

In this post, we're going to look at selfin a variety of every-day situations.

What is self?

You may have heard people say that everything in Ruby is an object. If that's true it means that every piece of code you write "belongs" to some object.

selfis a special variable that points to the object that "owns" the currently executing code. Ruby uses selfeverwhere:

For instance variables: @myvar For method and constant lookup When defining methods, classes and modules.

In theory, selfis pretty obvious. But in practice, it's easy for tricky situations to pop up. That's why I wrote this post.

Examples of self

We're going to step through several examples now. If the first ones seem too basic for you, just keep reading. They get more advanced.

Inside of an instance method

In the code below, reflectis an instance method. It belongs to the object we created via Ghost.new. So selfpoints to that object.

Remember, classes and modules are treated as objects in Ruby. So this behavior isn't that different from the instance method behavior we saw in the first example.

Inside of a class or module definition

One feature of Ruby that makes it such a good fit for frameworks like Rails is that you can execute arbitrary code inside class and module definitions. When you put code inside of a class/module definition, it runs just like any other Ruby code. The only real difference is the value of self.

As you can see below, selfpoints the the class or module that's in the process of being defined.

Chances are you've seen this popular shortcut for defining lots of class methods at once.

class Ghost class << self def method1enddef method2end endend

The class << foosyntax is actually pretty interesting. It lets you access an object's metaclass - which is also called the "singleton class" or "eigenclass." I plan on covering metaclasses more deeply in a future post. But for now, you just need to know that the metaclass is where Ruby stores methods that are unique to a specific object.

If you access selffrom inside the class << fooblock, you get the metaclass.