Bird
0
0

Given the following code, which option correctly filters only strings from the mixed array using .is_a??

hard📝 Application Q15 of 15
Ruby - Variables and Data Types
Given the following code, which option correctly filters only strings from the mixed array using .is_a??
items = ["apple", 42, :symbol, "banana", 3.14]
strings = items.select { |item| ??? }
Aitem.class != String
Bitem.class == String
Citem.is_a?(Integer)
Ditem.is_a?(String)
Step-by-Step Solution
Solution:
  1. Step 1: Understand filtering with .is_a?

    We want to select only elements that are strings, so we check if each item is a kind of String.
  2. Step 2: Compare options

    item.is_a?(String) uses .is_a?(String) which returns true for strings. item.class == String uses .class == String which also works but is less flexible if subclasses exist. Options C and D filter integers or non-strings, which is incorrect.
  3. Final Answer:

    item.is_a?(String) -> Option D
  4. Quick Check:

    Use .is_a?(String) to filter strings [OK]
Quick Trick: Use .is_a?(String) to include subclasses too [OK]
Common Mistakes:
  • Using .class == String and missing subclasses
  • Filtering wrong types by mistake
  • Forgetting question mark in .is_a?

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes