Check whether a variable is a string in Ruby

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

Is there anything more idiomatic than the following?

foo.class == String
6条回答
  •  陌清茗
    陌清茗 (楼主)
    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?).

提交回复
热议问题