尝试检查对象类型时出现 Ruby TypeError

标签 ruby typeerror

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

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.

为什么会这样?

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__]

最佳答案

错误消息很清楚:is_a? 需要一个类或模块,但您给它的是一个字符串。

你需要问 x.is_a 是不是?字符串,不是x.is_a? '字符串'

关于尝试检查对象类型时出现 Ruby TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48303041/

相关文章:

ruby - 堆场文档和 `define_method`

没有圆形的 Ruby eval

Ruby - 混合命名参数和位置参数,为什么顺序很重要?

python - 类型错误:不支持的操作数类型为 %: 'NoneType' 和 'str'

python - ZMQ 套接字类型错误 : unicode strings only Error: is there a fix?

ruby-on-rails - rake db :seed 验证失败

ruby - 如何让 xcode 在运行脚本时使用正确版本的 ruby​​?

python - 尝试使用 GData API 将图片从 Google App Engine 上传到 Picasa 时出现类型错误

python - 类型错误:必须使用 'method name' 实例作为第一个参数调用未绑定(bind)方法 'class name'(改为使用 str 实例)

javascript - 光滑的轮播 - 未捕获的类型错误 : undefined is not a function