Check whether a variable is a string in Ruby

后端 未结 6 613
陌清茗
陌清茗 2021-01-30 01:58

Is there anything more idiomatic than the following?

foo.class == String
6条回答
  •  失恋的感觉
    2021-01-30 02:23

    I think you are looking for instance_of?. is_a? and kind_of? will return true for instances from derived classes.

    class X < String
    end
    
    foo = X.new
    
    foo.is_a? String         # true
    foo.kind_of? String      # true
    foo.instance_of? String  # false
    foo.instance_of? X       # true
    

提交回复
热议问题