Using the .class method to determine if an object is what you are looking for
Public, Tricks, Ruby General
harrylevine
Created: Dec 10, 2014 Updated: May 28, 2015
Let's say that you want to use a given object if the object is an array; however, if the object is not an array (meaning it is a string, or a fixnum, etc.), then you do not want to use it.
You can use the .class
method with conditional logic to determine this. The catch is you need to also convert the .class
result into a string, like this:
a = [1, 2 , 3]
if a.class.to_s == 'Array'
puts "It is an array"
else
puts "It is not an array"
end
The above code would yield It is an array
. If you leave out the .to_s
, it would yield It is not an array
.
You can use instance_of?
. This returns true if the object is an instance of the given class, as in this example:
num = 10
puts(num.instance_of? Fixnum) #output true