Bird
0
0

to check this?

hard📝 Application Q15 of 15
Ruby - Inheritance
You have a method that accepts any object and should behave differently if the object is a String or a Numeric (including Integer and Float). Which Ruby code correctly uses is_a? or kind_of? to check this?
Aif obj.is_a?(String) puts "It's a string" elsif obj.is_a?(Numeric) puts "It's a number" else puts "Unknown type" end
Bif obj.kind_of?(String) puts "It's a string" elsif obj.kind_of?(Integer) puts "It's a number" else puts "Unknown type" end
Cif obj.is_a?(String) puts "It's a string" elsif obj.kind_of?(Float) puts "It's a number" else puts "Unknown type" end
Dif obj.is_a?(Object) puts "It's a string" elsif obj.is_a?(Numeric) puts "It's a number" else puts "Unknown type" end
Step-by-Step Solution
Solution:
  1. Step 1: Understand class hierarchy

    Numeric is a superclass of Integer and Float, so checking is_a?(Numeric) covers all number types.
  2. Step 2: Analyze each option

    if obj.is_a?(String) puts "It's a string" elsif obj.is_a?(Numeric) puts "It's a number" else puts "Unknown type" end correctly checks for String and then Numeric.
    if obj.kind_of?(String) puts "It's a string" elsif obj.kind_of?(Integer) puts "It's a number" else puts "Unknown type" end checks Integer only, missing Float.
    if obj.is_a?(String) puts "It's a string" elsif obj.kind_of?(Float) puts "It's a number" else puts "Unknown type" end checks only Float, missing Integer.
    if obj.is_a?(Object) puts "It's a string" elsif obj.is_a?(Numeric) puts "It's a number" else puts "Unknown type" end checks Object first, which is always true, so logic fails.
  3. Final Answer:

    Option A code correctly distinguishes String and all Numeric types -> Option A
  4. Quick Check:

    Use Numeric superclass to cover all numbers [OK]
Quick Trick: Check against Numeric to cover all number types [OK]
Common Mistakes:
  • Checking only Integer or Float separately
  • Using Object which is always true
  • Mixing is_a? and kind_of? incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes