0
0
Rubyprogramming~15 mins

Type checking with .class and .is_a? in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
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 String
Use a for loop with variable item to iterate over items
Inside the loop, use item.class == type_to_check to check type and store result in class_check
Inside the loop, use item.is_a?(type_to_check) to check type and store result in is_a_check
Print 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
1
Create the items array
Create an array called items with these exact elements: 42, "apple", 3.14, :symbol, and [1, 2, 3]
Ruby
Need a hint?

Use square brackets [] to create an array and separate elements with commas.

2
Set the type_to_check variable
Create a variable called type_to_check and set it to the class String
Ruby
Need a hint?

Assign the class String directly to the variable.

3
Use a for loop to check types
Use a for loop with variable item to iterate over items. Inside the loop, use item.class == type_to_check to check type and store the result in class_check. Also use item.is_a?(type_to_check) to check type and store the result in is_a_check
Ruby
Need a hint?

Use parentheses around item.class == type_to_check to store the boolean result.

4
Print the results inside the loop
Inside the for loop, print the item, class_check, and is_a_check values in each iteration using puts
Ruby
Need a hint?

Use string interpolation with #{} inside puts to show values.