How to use is_a? Method In Ruby
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
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