Search code examples
rubynet-http

Why does 'Net::HTTPUnknownResponse.kind_of? Net::HTTPResponse' return 'false'?


I am using library net/http, and am trying to check if a response is type Net::HTTPResponse. I tried:

Net::HTTPUnknownResponse.kind_of? Net::HTTPResponse
# => false

What's wrong?


Solution

  • kind_of? is used to check whether an object is an instance of a given class, e.g.

    1.kind_of? Numeric
    #=> true
    

    You can't just replace the instance with its class:

    Integer.kind_of? Numeric
    #=> false
    

    Because Integer (the class) is an instance of Class:

    Integer.kind_of? Class
    #=> true
    

    Instead you can use < to check whether the receiver is a subclass of a given class (or module, it's not limited to classes):

    Integer < Numeric
    #=> true
    
    Integer < Comparable
    #=> true
    

    In your specific case:

    require 'net/http'
    
    Net::HTTPUnknownResponse < Net::HTTPResponse
    #=> true
    

    Note that the above code will always return true (unless you change the class hierarchy). If you are using the net/http library, your response object should be an instance of Net::HTTPUnknownResponse, not the class itself.