尝试检查对象类型时的Ruby TypeError

时间:2018-01-17 14:06:59

标签: ruby typeerror

虽然我有一个字符串对象,但在检查对象类型时,我无法检索布尔值。

ruby-doc.org

  

is_a?(class)→true或false如果class是类,则返回true   obj,或者如果class是包含的obj或模块的超类之一   在obj。

为什么会这样?

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/ruby@2.2/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__]

1 个答案:

答案 0 :(得分:4)

错误消息很明确:is_a?需要一个类或模块,但是你给它一个字符串。

您需要询问x.is_a? String,而不是x.is_a? 'String'