Let’s learn about
singleton_class with an example. I have a
Car which knows to
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
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 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
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.