How to use Class method In Ruby

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 = "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

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

Similar Reads

Using Class method

The Class method returns the class name of an object....

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....

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....

Contact Us