Menu
Coddy logo textTech

Checking Data Types

Part of the Fundamentals section of Coddy's Ruby journey — lesson 8 of 88.

Ruby provides the .class method to check the data type of any object.

The .class method is called on a variable or value and returns the class (data type) of that object. Simply append .class to your variable name:

my_variable = 42
my_variable.class

This will return Integer because the variable contains an integer value. Similarly, .class will return String for text data, Float for decimal numbers, TrueClass for true, FalseClass for false, and Symbol for symbols.

You can combine .class with puts to display the data type to the console, making it easy to verify what kind of data you're working with at any point in your program.

challenge icon

Challenge

Easy

Create four different variables with different data types, then use the .class method to check and display the data type of each variable.

First, create a variable called score and assign it the value 88.5. Then create a variable called student_name and assign it the value "Sarah". Next, create a variable called passed and assign it the value true. Finally, create a variable called year and assign it the value 2024.

After creating all four variables, use the .class method combined with puts to display the data type of each variable in this exact order: score, student_name, passed, and year.

Cheat sheet

Use the .class method to check the data type of any object:

my_variable = 42
my_variable.class

This returns the class (data type) of the object:

  • Integer for whole numbers
  • Float for decimal numbers
  • String for text data
  • TrueClass for true
  • FalseClass for false
  • Symbol for symbols

Combine .class with puts to display the data type:

puts my_variable.class

Try it yourself

# TODO: Create four variables with the specified values and data types

# TODO: Use .class method with puts to display the data type of each variable
# Remember to display them in this order: score, student_name, passed, year
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals