Check whether a variable is a string in Ruby

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

Is there anything more idiomatic than the following?

foo.class == String
相关标签:
6条回答
  • 2021-01-30 02:22

    In addition to the other answers, Class defines the method === to test whether an object is an instance of that class.

    • o.class class of o.
    • o.instance_of? c determines whether o.class == c
    • o.is_a? c Is o an instance of c or any of it's subclasses?
    • o.kind_of? c synonym for *is_a?*
    • c === o for a class or module, determine if *o.is_a? c* (String === "s" returns true)
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-30 02:43
    foo.instance_of? String
    

    or

    foo.kind_of? String 
    

    if you you only care if it is derrived from String somewhere up its inheritance chain

    0 讨论(0)
  • 2021-01-30 02:46

    You can do:

    foo.instance_of?(String)
    

    And the more general:

    foo.kind_of?(String)
    
    0 讨论(0)
  • 2021-01-30 02:46

    I think a better way is to create some predicate methods. This will also save your "Single Point of Control".

    class Object
     def is_string?
       false
     end
    end
    
    class String
     def is_string?
       true
     end
    end
    
    print "test".is_string? #=> true
    print 1.is_string?      #=> false
    

    The more duck typing way ;)

    0 讨论(0)
  • 2021-01-30 02:48

    A more duck-typing approach would be to say

    foo.respond_to?(:to_str)
    

    to_str indicates that an object's class may not be an actual descendant of the String, but the object itself is very much string-like (stringy?).

    0 讨论(0)
提交回复
热议问题