Ruby singleton_class

Let’s learn about singleton_class with an example. I have a Car which knows to drive.

class Car
  def drive
    puts "I am driving"
  end
end

car = Car.new
car.drive # I am driving

Cool so what! Now at later point of time I want to add honk to my car only when it is stuck in traffic. I don’t want it to be added for every Car object.

There might be more than one way of doing this in ruby but in the interest of this post i will implement this with singleton_class.  Ruby singleton_class inserts a new anonymous class into the inheritance hierarchy as a container and adds the new method to it.

class Car
  def drive
    puts "I am driving"
  end
end

module Honking
  def honk
    puts "Get away on my way"
  end
end

car = Car.new

traffic = true # more logic here

if traffic
  car.singleton_class.include(Honking)  
end

car.honk

p car.singleton_methods # [:honk]

race_car = Car.new
race_car.honk # undefined method `honk'

singleton_class creates a new singleton class if car does not have one. From then what ever changes you make on that is going to be affected to that particular class. Thats the reason race_car doesn’t know anything about honk.

I also used singleton_classto add additional validations to the object in a specific context.

You can check singleton methods on a class using singleton_methods.

Happy coding!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.