← Back to context

Comment by systemnate

15 hours ago

Using #respond_to? is normally a code smell. The point of duck typing is exactly that it allows you to avoid checking the type of a class. As long as the object responds to the correct messages, the type does not matter.

#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