How to Use Self in Ruby

09/20/2021

Contents

In this article, you will learn how to use self in Ruby.

Using the self keyword

In Ruby, the self keyword refers to the current object or instance of a class. It can be used in different ways depending on the context. Here are some common uses of self in Ruby:

Accessing instance variables

When you define an instance variable within a class, you can access it using self within an instance method. For example:

class Person
  def initialize(name)
    @name = name
  end

  def say_hello
    puts "Hello, my name is #{self.name}."
  end

  def name
    @name
  end
end

person = Person.new("Alice")
person.say_hello #=> Hello, my name is Alice.

Calling other instance methods

You can use self to call other instance methods within a class. For example:

class Person
  def initialize(name)
    @name = name
  end

  def say_hello
    introduce
  end

  def introduce
    puts "Hello, my name is #{self.name}."
  end

  def name
    @name
  end
end

person = Person.new("Alice")
person.say_hello #=> Hello, my name is Alice.

Creating class methods

You can use self to define class methods within a class. Class methods are methods that are called on the class itself, rather than on an instance of the class. For example:

class Person
  @@count = 0

  def initialize(name)
    @name = name
    @@count += 1
  end

  def self.count
    @@count
  end
end

person1 = Person.new("Alice")
person2 = Person.new("Bob")

puts Person.count #=> 2

Creating class variables

You can use self to define class variables within a class. Class variables are variables that are shared by all instances of a class. For example:

class Person
  @@count = 0

  def initialize(name)
    @name = name
    @@count += 1
  end

  def self.count
    @@count
  end

  def self.reset_count
    @@count = 0
  end
end

person1 = Person.new("Alice")
person2 = Person.new("Bob")

puts Person.count #=> 2

Person.reset_count

puts Person.count #=> 0

These are just a few examples of how to use self in Ruby. Understanding self is important for writing object-oriented code in Ruby.