2

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
Montenegrodr
  • 1,597
  • 1
  • 16
  • 30

1 Answers1

4

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.

Stefan
  • 109,145
  • 14
  • 143
  • 218