Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Enumerable and Collection Processing
What will be the output of this Ruby code?
words = ["apple", "banana", "cherry", "date"]
filtered = words.reject { |w| w.length > 5 }
p filtered
A["banana", "cherry"]
B["apple", "banana", "cherry", "date"]
C[]
D["apple", "date"]
Step-by-Step Solution
Solution:
  1. Step 1: Understand the reject condition

    Reject words where length is greater than 5, so remove words longer than 5 characters.
  2. Step 2: Identify words kept

    "banana" and "cherry" have length 6 and 6, so removed; "apple" (5) and "date" (4) remain.
  3. Final Answer:

    ["apple", "date"] -> Option D
  4. Quick Check:

    reject length > 5 = keep length ≤ 5 [OK]
Quick Trick: Reject removes elements matching condition, keeps others [OK]
Common Mistakes:
  • Mixing up which words are removed
  • Assuming reject modifies original array
  • Confusing length comparison operators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes