How to Check the Data Type of a Variable in Ruby?
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.
Table of Content
- Using Class method
- Using is_a? Method
- Using kind_of? Method
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
.
# 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 = "w3wiki"
puts "Data type of 'str': #{str.class}"
# Example 3: Array
arr = [1, 2, 3]
puts "Data type of 'arr': #{arr.class}"
Output
Data 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
.
# 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 = "w3wiki"
# 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)}"
Output
Is '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.
# 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 = "w3wiki"
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
Output
Is 'mum' an integer? true Is 'str' a String? true Is 'arr' an Array? true
Contact Us