Check whether a variable is a string in Ruby

davidchambers picture davidchambers · Oct 13, 2011 · Viewed 128.4k times · Source

Is there anything more idiomatic than the following?

foo.class == String

Answer

Candide picture Candide · Oct 13, 2011

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