Check whether a variable is a string in Ruby
Is there anything more idiomatic than the following?
foo.class == String
Solution 1:
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
Solution 2:
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?).
Solution 3:
You can do:
foo.instance_of?(String)
And the more general:
foo.kind_of?(String)