Object Scope and Self

Learn about the scope of an object, the scope of an instance method, and the self keyword.

Remember that when Ruby finds a method call, it deviates from the normal control flow which goes from top to bottom. Instead, it jumps into the method body.

We also learned that this method body has its own scope, like a shiny new room where local variables from other scopes are invisible. Instead, it has its own local variables, some of which might be defined through the method’s arguments.

We also learned that all instance variables inside an object and all its other methods are also visible.

Later, we’ll look at that mysterious top-level object that Ruby enters when it starts executing a program.

We’re now finally ready to put all these things together and introduce a new keyword: self.

The object scope

In Ruby, there are even more scopes than just the local method’s scope. There’s the method’s local scope, which holds all local variables, and there’s the object’s scope, which holds all instance variables and method names.

When Ruby’s control flow jumps into a method, both scopes are visible at the same time. For any given name, Ruby first checks the local scope and then the object scope.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy