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.

class Ghost def reflect self endendg = Ghost.newg.reflect == g # => true Inside of a class method

For this example, reflectis a class method of Ghost. With class methods, the class itself "owns" the method. selfpoints to the class.

class Ghost def self.reflect self endendGhost.reflect == Ghost # => true

It works the same with "class" methods inside of modules. For example:

module Ghost def self.reflect puts self endend Ghost.reflect == Ghost # => true

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.

class Ghost self == Ghost # => trueend module Mummy self == Mummy # => trueend Inside mixin methods

Mixed-in methods behave just like "normal" instance or class methods when it comes to self. This makes sense. Otherwise the mixin wouldn't be able to interact with the class you mixed it into.

Instance methods

Even though the reflectmethod was defined in the module, its selfis the instance of the class it was mixed into.

module Reflection def reflect self endend class Ghost include Reflectionendg = Ghost.newg.reflect == g # => true Class methods

When we extenda class to mix in class methods, selfbehaves exactly like it does in normal class methods.

module Reflection def reflect self endend class Ghost extend ReflectionendGhost.reflect == Ghost # => true Inside the metaclass

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.

class << "test" puts self.inspectend# => #<Class:#<String:0x007f8de283bd88> Outside of any class

If you're running code outside of any class, Ruby still provides self. It points to "main", which is an instance of Object:

puts self.inspect # => main


分享给朋友:
您可能感兴趣的文章:
随机阅读: