DEV Community

Cover image for 49 Days of Ruby: Day 24 - Self
Ben Greenberg
Ben Greenberg

Posted on

49 Days of Ruby: Day 24 - Self

Welcome to day 24 of the 49 Days of Ruby! 🎉

Today, we are going to discuss the self. No, not yourself or myself, but rather the self in Ruby.

What is the self?

The self in Ruby is a special keyword that enables you to access the current object.

What does that mean in practical terms? Let's take a look at an example:

class Coffee
  def identify_me
    puts self
  end
end

> Coffee.new.identify_me

# => <Coffee:...>
Enter fullscreen mode Exit fullscreen mode

In the case of the new Coffee class, the method defined therein is within the context of that class. Thus, the self is Coffee.

Why is this useful?

There are a few reasons why understanding self is important. We'll focus on two.

The first is disambiguation. The self lets us know exactly where we are inside our code. No guessing required. We may be in an instance of a class, inside a class itself, or in main, which is the name of the most top-level object.

The more we understand about where we are, the more empowered we are to write effective code.

The second is getting to write class-level methods.

Did you notice in the example above of the Coffee class I needed to instantiate a Coffee instance before invoking #indentify_me?

Take a look at this:

class Coffee
  def self.identify_me
    puts self
  end
end
Enter fullscreen mode Exit fullscreen mode

By appending self to the #identify_me method we mark it as a class method, not an instance method. This means we can call Coffee.identify_me directly without needing to instantiate a new Coffee instance first.

That sums up our conversation on the self for today! There's a lot more to discover about it. Feel free to share your learnings with the community, too!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (1)

Collapse
 
alishi973 profile image
Ali Shirzad

Nice, keep going Ben! <3