0
0
Rubyprogramming~10 mins

Is_a? and kind_of? for type checking in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if the variable obj is a String using is_a?.

Ruby
obj = "hello"
puts obj.[1](String)
Drag options to blanks, or click blank then click option'
Ais_a?
Bkind_of?
Cinstance_of?
Dclass
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'instance_of?' which only checks exact class, not subclasses.
Using 'class' which returns the class object, not a boolean.
2fill in blank
medium

Complete the code to check if num is a Numeric type using kind_of?.

Ruby
num = 42
if num.[1](Numeric)
  puts "It's a number!"
end
Drag options to blanks, or click blank then click option'
Ais_a?
Binstance_of?
Ckind_of?
Drespond_to?
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'instance_of?' which does not consider subclasses.
Using 'respond_to?' which checks for methods, not class type.
3fill in blank
hard

Fix the error in the code to correctly check if arr is an Array using is_a?.

Ruby
arr = [1, 2, 3]
if arr.[1](Array)
  puts "It's an array!"
end
Drag options to blanks, or click blank then click option'
Ais_a
Bis_a?
Ckind_of?
Dkind_of
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the question mark in the method name.
Using 'kind_of' without question mark.
4fill in blank
hard

Fill both blanks to create a method that returns true if obj is a String or a subclass of String.

Ruby
def string_check(obj)
  obj.[1](String) || obj.[2](String)
end
Drag options to blanks, or click blank then click option'
Ais_a?
Binstance_of?
Ckind_of?
Dclass
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'instance_of?' which only checks exact class.
Using 'class' which returns the class object, not a boolean.
5fill in blank
hard

Fill all three blanks to create a hash that maps objects to their type check results using is_a? and kind_of?.

Ruby
obj1 = [1, 2, 3]
obj2 = {a: 1}
obj3 = "test"
results = {
  obj1: obj1.[1],
  obj2: obj2.[2](Hash),
  obj3: obj3.[3](String)
}
Drag options to blanks, or click blank then click option'
Ais_a?
Bkind_of?
Cinstance_of?
Dclass
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'instance_of?' which does not consider subclasses.
Using 'class' expecting a boolean result.