How to Determine the type of an object in Ruby?
In this article, we will discuss how to determine the type of an object in Ruby. We can determine the type of an object through different methods ranging from using class
method and is_a?
method to instance_of?
method.
Table of Content
- Determining the type of an object using class method
- Determining the type of an object using is_a? method
- Determine the type of an object using instance_of? method
Determining the type of an object using the class method
The class
method returns the class of the object.
Syntax:
object.class
Example: In this example, we use the class
method to determine the type of object
# Determine the type of object using class method
def type_of_object(obj)
obj.class
end
#Driver code
obj1 = "Hello"
obj2 = 123
obj3 = [1, 2, 3]
obj4 = { key: "value" }
# Output the type
puts type_of_object(obj1) # Output: String
puts type_of_object(obj2) # Output: Integer
puts type_of_object(obj3) # Output: Array
puts type_of_object(obj4) # Output: Hash
Output
String Integer Array Hash
Determining the type of an object using is_a? method
The is_a?
method checks if the object is an instance of a specified class or module
Syntax:
object.is_a?(Class)
Example: In this example,we use the is_a? method to check the type of object .
# Determine the type of object using is_a? method
def type_of_object(obj)
if obj.is_a?(String)
"String"
elsif obj.is_a?(Integer)
"Integer"
elsif obj.is_a?(Array)
"Array"
elsif obj.is_a?(Hash)
"Hash"
else
"Unknown"
end
end
#Driver code
obj1 = "Hello"
obj2 = 123
obj3 = [1, 2, 3]
obj4 = { key: "value" }
# Output the type
puts type_of_object(obj1) # Output: String
puts type_of_object(obj2) # Output: Integer
puts type_of_object(obj3) # Output: Array
puts type_of_object(obj4) # Output: Hash
Output
String Integer Array Hash
Determine the type of an object using instance_of? method
The instance_of?
method checks if the object is an instance of a specific class
Syntax:
object.instance_of?(Class)
Example: In this example we use the instance_of? method to check the type of an object in class.
# Determine the type of object using instance_of? method
def type_of_object(obj)
if obj.instance_of?(String)
"String"
elsif obj.instance_of?(Integer)
"Integer"
elsif obj.instance_of?(Array)
"Array"
elsif obj.instance_of?(Hash)
"Hash"
else
"Unknown"
end
end
obj1 = "Hello"
obj2 = 123
obj3 = [1, 2, 3]
obj4 = { key: "value" }
puts type_of_object(obj1) # Output: String
puts type_of_object(obj2) # Output: Integer
puts type_of_object(obj3) # Output: Array
puts type_of_object(obj4) # Output: Hash
Output
String Integer Array Hash
Contact Us