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.classThis 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
EasyCreate 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.classThis returns the class (data type) of the object:
Integerfor whole numbersFloatfor decimal numbersStringfor text dataTrueClassfortrueFalseClassforfalseSymbolfor symbols
Combine .class with puts to display the data type:
puts my_variable.classTry 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, yearThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False