Wings
Wings

Reputation: 1026

Ruby TypeError when trying to check object type

Although I have a string object, I am unable to retrieve a boolean when checking what the object type is.

ruby-doc.org

is_a?(class) → true or false Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

Why is this happening?

irb(main):105:0> p server[0]['role'].class
    String
    => String

irb(main):106:0> p server[0]['role'].is_a? 'String'
TypeError: class or module required
    from (irb):103:in `is_a?'
    from (irb):103
    from /usr/local/opt/[email protected]/bin/irb:11:in `<main>'

irb(main):107:0> p server[0]['role'].methods
[:<=>, :==, :===, :eql?, :hash, :casecmp, :+, :*, :%, :[], :[]=, :insert, :length, :size, :bytesize, :empty?, :=~, :match, :succ, :succ!, :next, :next!, :upto, :index, :rindex, :replace, :clear, :chr, :getbyte, :setbyte, :byteslice, :scrub, :scrub!, :freeze, :to_i, :to_f, :to_s, :to_str, :inspect, :dump, :upcase, :downcase, :capitalize, :swapcase, :upcase!, :downcase!, :capitalize!, :swapcase!, :hex, :oct, :split, :lines, :bytes, :chars, :codepoints, :reverse, :reverse!, :concat, :<<, :prepend, :crypt, :intern, :to_sym, :ord, :include?, :start_with?, :end_with?, :scan, :ljust, :rjust, :center, :sub, :gsub, :chop, :chomp, :strip, :lstrip, :rstrip, :sub!, :gsub!, :chop!, :chomp!, :strip!, :lstrip!, :rstrip!, :tr, :tr_s, :delete, :squeeze, :count, :tr!, :tr_s!, :delete!, :squeeze!, :each_line, :each_byte, :each_char, :each_codepoint, :sum, :slice, :slice!, :partition, :rpartition, :encoding, :force_encoding, :b, :valid_encoding?, :ascii_only?, :unpack, :encode, :encode!, :to_r, :to_c, :unicode_normalize, :unicode_normalize!, :unicode_normalized?, :to_json, :to_json_raw, :to_json_raw_object, :>, :>=, :<, :<=, :between?, :nil?, :!~, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :singleton_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]

Upvotes: 1

Views: 411

Answers (1)

user229044
user229044

Reputation: 239311

The error message is clear: is_a? expects a class or module, but you're giving it a string.

You need to ask if x.is_a? String, not x.is_a? 'String'.

Upvotes: 4

Related Questions