Ruby Singleton Methods at Depth
A singleton method belongs to one object and to no other. This lesson builds them in two ways and lists what an object holds.
One dog learns a trick
def rex.trick defines trick on rex alone. Fido is a dog too, and fido answers false when asked about trick.
class Dog
end
rex = Dog.new
fido = Dog.new
def rex.trick
puts "Roll over"
end
rex.trick
puts fido.respond_to?(:trick)Built from a name with define_singleton_method
define_singleton_method takes the name greet as a symbol and a block for the body. The dog answers greet right away.
class Dog
end
dog = Dog.new
dog.define_singleton_method(:greet) do
puts "Hello from this dog"
end
dog.greetListing singleton methods in order
The dog gains trick and greet in two different ways. singleton_methods lists both names, and sort prints them in a steady order.
class Dog
end
dog = Dog.new
def dog.trick
puts "Roll over"
end
dog.define_singleton_method(:greet) do
puts "Hello"
end
puts dog.singleton_methods.sortExample
class Bird
end
pip = Bird.new
skye = Bird.new
def pip.song
puts "Morning song"
end
pip.define_singleton_method(:call) do
puts "Sharp call"
end
pip.song
pip.call
puts skye.respond_to?(:song)
puts pip.singleton_methods.sortKey points
- def followed by an object and a method name defines a method on that object alone.
- define_singleton_method builds a singleton method from a name and a block.
- singleton_methods lists the names of the singleton methods an object holds.
- Sorting that list gives a steady order for printing.
- Other objects of the same class answer false to respond_to? for the method.
In this example, pip gains song with a plain definition and call with define_singleton_method. Skye shares the Bird class and still answers false for song. The sorted list at the end names the two methods pip holds.
Note
A singleton method never spreads to the rest of its class.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method builds a singleton method from a name and a block?