# is_a? vs respond_to?

I am working on some code which checks whether or not to unlink a file on the basis of the class:

File.unlink(file.path) if file.is_a? File


I think it would be more idiomatic to check whether the object responds to the unlink message:

File.unlink(file.path) if file.respond_to? :unlink


Is there any good reason to prefer the is_a? approach?

• I love my static type checker. Oct 14, 2013 at 3:00
• can you provide some more context ? This kind of code is usually avoidable with a different OO design. I recommend that you read Some of Avdi Grimm's talks about "confident code" that provide nice insights on how to code comfortably in a duck-typing environment.
– m_x
Oct 22, 2013 at 7:25
• +1 to the different design, that's on the cards. The existing code does this is_a? hack. I thought that perhaps respond_to? would be a more idiomatic approach in the interim. Oct 22, 2013 at 21:50

Given that on some file systems a directory is simply a File with special attributes (or to put it another way a specialized file), does it really matter? Unlink it if it can be unlinked if that is what you want to do. If it can't be unlinked, why would you bother? And why would you care what it is? If you care what it is, then use is_a? If the inode can be unlinked, unlink it.
• that's what I was thinking, hence the change to respond_to? Oct 23, 2013 at 2:22