How to use kind_of? Method In Ruby
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
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
Contact Us