Comment by jaggederest
12 hours ago
#respond_to? is fine, it's really more #is_a? that is a code smell, in my opinion. As long as you're dispatching based on #respond_to? (i.e. "does this respond to each") by calling the method you're checking, when it does respond, you're fine as far as duck typing goes. It's when you check #is_a? and then dispatch based on type where things get weird.
An example I always used to use was something like a method that could take a single item or a collection:
def unpicky(something)
if something.respond_to?(:each)
# unpack using each or recurse to something.each do |item| unpicky(item) end
else
# main body
end
end
No comments yet
Contribute on Hacker News ↗