Bird
0
0

Find the bug in this Ruby code:

medium📝 Debug Q7 of 15
Ruby - Variables and Data Types
Find the bug in this Ruby code:
def check_type(obj)
  if obj.is_a?(Array)
    puts "Array detected"
  elsif obj.class == Hash
    puts "Hash detected"
  else
    puts "Unknown type"
  end
end

class MyHash < Hash; end

check_type(MyHash.new)
ANo bug, code works correctly
BMissing return statement in method
CUsing obj.class == Hash instead of obj.is_a?(Hash)
DWrong method call syntax
Step-by-Step Solution
Solution:
  1. Step 1: Understand type checks used

    First condition uses .is_a?(Array), second uses .class == Hash.
  2. Step 2: Identify inconsistency and potential bug

    .class == Hash fails if obj is subclass of Hash; .is_a?(Hash) is safer and consistent.
  3. Final Answer:

    Using obj.class == Hash instead of obj.is_a?(Hash) -> Option C
  4. Quick Check:

    Use .is_a? for subclass-safe checks [OK]
Quick Trick: Prefer .is_a? over .class == for type checks [OK]
Common Mistakes:
MISTAKES
  • Mixing .class == with .is_a?
  • Ignoring subclass behavior
  • Assuming no bug if code runs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes