Ruby - Checking existance of Singleton Methods

Introduction

The Object class has a singleton_methods method that returns an array of singleton method names.

You can test a method name for inclusion using the Array class's include? method.

myBox = Box.new( "Star Prize" ) 
def myBox.sayHi 
    puts( "hi!" ) 
end 

The sayHi method should be called when the myBox box is opened.

This bit of code ensures that this method is not called when some other box is opened:

if item.singleton_methods.include?("sayHi") then 
    item.sayHi 
end     

An alternative way of checking the validity of a method would be to pass that method name as a symbol (an identifier preceded by a colon) to the Object class's respond_to? method:

if item.respond_to?( :sayHi ) then 
   item.sayHi 
end     

Related Topic