Check whether a variable is a string in Ruby

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

Is there anything more idiomatic than the following?

foo.class == String
6条回答
  •  没有蜡笔的小新
    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 ;)

提交回复
热议问题