How to Check the Data Type of a Variable in Ruby?
Last Updated :
02 Apr, 2024
In this article, we will discuss how to check the data type of a variable in Ruby. We can check the data types of a variable through different methods ranging from class to kind_of method in Ruby.
Using Class method
The Class
method returns the class name of an object.
Syntax:
variable.class
Example:
In this example, we use the class method on num,string and an array
to determine its data type, which returns Integer
.
Ruby
# Check the Data Type of a Variable using 'class' method
# Example 1: Integer
num = 10
puts "Data type of 'num': #{num.class}"
# Example 2: String
str = "GeeksforGeeks"
puts "Data type of 'str': #{str.class}"
# Example 3: Array
arr = [1, 2, 3]
puts "Data type of 'arr': #{arr.class}"
OutputData type of 'num': Integer
Data type of 'str': String
Data type of 'arr': Array
Using is_a?
Method
The is_a? method is used to check if an object is an instance of a specific class or its subclass.
Syntax:
variable.is_a?(ClassName)
Example:
In this example we use the is_a?
method on num,string and array
to check if it is an instance of the Integer,string and array
class.The method returns true
if num,str,array
are instance of Integer,string and array
, otherwise false
.
Ruby
# Check the Data Type of a Variable Using 'is_a?' method
# Example 1: Integer
num = 10
# Checking if 'num' is an Integer
puts "Is 'num' an Integer? #{num.is_a?(Integer)}"
# Example 2: String
str = "GeeksforGeeks"
# Checking if 'str' is a String
puts "Is 'str' a String? #{str.is_a?(String)}"
# Example 3: Array
arr = [1, 2, 3]
puts "Is 'arr' an Array? #{arr.is_a?(Array)}"
OutputIs 'num' an Integer? true
Is 'str' a String? true
Is 'arr' an Array? true
Using kind_of?
Method
The kind_of? method is used to check if an object is an instance of a specific class or its subclass.The method returns true if num,str,array are instance of Integer,string and array, otherwise false.
Syntax:
variable.kind_of?(ClassName)
Example:
In this example we use the kind_of?
method on num,str,arr
to check if it is an instance of the integer,string and array
class.
Ruby
# Check the Data Type of a Variable Using 'kind_of?' method
# Example 1: Integer
num = 10
puts "Is 'mum' an integer? #{num.kind_of?(Integer)}" # Output: Is 'num' an Integer? true
# Example 2: String
str = "GeeksforGeeks"
puts "Is 'str' a String? #{str.kind_of?(String)}" # Output: Is 'str' a String? true
# Example 3: Array
arr = [1, 2, 3]
# Checking if 'arr' is an Array
puts "Is 'arr' an Array? #{arr.kind_of?(Array)}" # Output: Is 'arr' an Array? true
OutputIs 'mum' an integer? true
Is 'str' a String? true
Is 'arr' an Array? true
Share your thoughts in the comments
Please Login to comment...