Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a variable is a string in Ruby

People also ask

How do you check if a variable is a string in Ruby?

is_a? and kind_of? will return true for instances from derived classes. Quick aside: if you use this in conditional logic you need to use parentheses; eg, if foo. is_a?(String) && ...

How do I check if a string is a variable?

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string. In all other cases the variable isn't a string. Copied!

How do I find the variable type in Ruby?

The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object. class . Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.


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

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?).


You can do:

foo.instance_of?(String)

And the more general:

foo.kind_of?(String)

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