Application 2024-05-15

About Ruby's Singleton Classes and Singleton Methods

Explore Ruby singleton classes, singleton methods, class methods, and object-specific method definitions for advanced metaprogramming.

Read in: ja
About Ruby's Singleton Classes and Singleton Methods

Overview

This post discusses Ruby's singleton classes and singleton methods.

Singleton Classes

A singleton class refers to a class that is only valid for a specific object.

class Greet
  def say_hi
    puts 'Hi'
  end
end

greet = Greet.new

# Singleton Class
class << greet
  # Singleton Method
  def say_bye
    puts 'Bye'
  end
end

greet.say_hi # => Hi
greet.say_bye # => Bye
p greet.singleton_methods # => [:say_bye]
singleton_class = greet.singleton_class
puts singleton_class # => #<Class:#<Greet:0x00007f8b1b0>>

Singleton Methods

A singleton method is a method that is only valid for a specific object.

class Greet
  def self.say_hi
    puts "Hi"
  end
end

Greet.say_hi # => Hi

obj = Greet.new

# Singleton Method
def obj.say_bye
  puts "Bye"
end

obj.say_bye # => Bye
p obj.singleton_methods # => [:say_bye]

Since singleton methods are methods that only a specific object possesses, they are only valid for that object.

class Greet; end

obj1 = Greet.new
obj2 = Greet.new

def obj1.say_hi
  puts "Hi"
end

obj1.say_hi # Hi
obj2.say_hi # NoMethodError

Class methods are essentially singleton methods.

class Greet
  # Class Method Definition
  class << self
    def say_hi
      puts "Hello"
    end
  end
end

puts Greet.say_hi

# Class methods can also be defined outside the class definition
class Greet; end
class << Greet
  def say_hi
    puts "Hello"
  end
end

puts Greet.say_hi

# Class methods can also be defined as follows
class Greet
  def self.say_hi
    puts "Hi"
  end
end

References

Tags: Ruby
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles