HiveBrain v1.2.0
Get Started
← Back to all entries
principlerubyMinor

is_a? vs respond_to?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
is_arespond_tostackoverflow

Problem

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?

Solution

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.

Context

StackExchange Code Review Q#32662, answer score: 5

Revisions (0)

No revisions yet.