Type checking with .class and .is_a? in Ruby
📖 Scenario: Imagine you are building a simple program that handles different types of items in a store. You want to check the type of each item to decide how to process it.
🎯 Goal: You will create a list of items with different types, set a type to check for, use .class and .is_a? methods to check item types, and print the results.
📋 What You'll Learn
Create an array called
items with exact elements: 42, "apple", 3.14, :symbol, and [1, 2, 3]Create a variable called
type_to_check and set it to StringUse a
for loop with variable item to iterate over itemsInside the loop, use
item.class == type_to_check to check type and store result in class_checkInside the loop, use
item.is_a?(type_to_check) to check type and store result in is_a_checkPrint the item,
class_check, and is_a_check in each loop iteration💡 Why This Matters
🌍 Real World
Type checking helps programs decide how to handle different kinds of data, like numbers, text, or lists, which is common in many software applications.
💼 Career
Understanding type checking is important for debugging, writing safe code, and working with object-oriented programming in Ruby and other languages.
Progress0 / 4 steps