DEV Community

Cover image for Me, MySelf, & Self.

Me, MySelf, & Self.

patrickco profile image Patrick-co ・2 min read

It is week five into my journey with Flatiron, and I can confidently say I have learned much considering I had very minimal knowledge in the matter. I still have a long way to go, but every step takes me that much closer to reaching my goals.

In this blog post I do not want to talk too much about myself, as in me, but of 'self' which is a keyword that can be found within the Ruby language.
I, myself, am still having a bit of trouble grasping the full extent of this confusing keyword, so let's dive into it together.

There are four types of variables in Ruby:
Instance variables which uses the symbol @
Class variables which will use the the symbol @@
Local variables
Global variables

What is Self in Ruby, and how can we use it?

They keyword 'self' in Ruby gives us access to the current object and is the default receiver of method calls for which no explicit receiver is specified.
When you use the self keyword within an object it points at itself. Using self inside an instance or class method refers to the same object the method is being called on.

-In a method, the object on which the method was called is 'self'

Alt Text

-In a class or module, 'self' is the class or module object being defined
Alt Text

If your code is inside and instance method, 'self' is an instance of that class. In other word's self is an object.

Alt Text

Why do we use 'self'

We would want to use 'self' because we don’t want to use the class name for each method definition. Self makes our code easier to change if we change the class. And it makes the code less noisy and easy to read.

The concept of 'self' was and still continues to be a challenge to me, but good thing I love a challenge. If you are like myself, remember to be patient with yourself, and take your learning step by step. You will definitely thank yourself in the long run.

‘You don’t learn to walk by following rules. You learn by doing, and by falling over.’ –Richard Branson

Discussion (0)

Editor guide