Bird
0
0

Given the array arr = [false, nil, 0, "", [], true], which Ruby code snippet correctly filters out falsy values?

hard📝 Application Q8 of 15
Ruby - Operators and Expressions
Given the array arr = [false, nil, 0, "", [], true], which Ruby code snippet correctly filters out falsy values?
Afiltered = arr.reject { |v| v == false || v.nil? }
Bfiltered = arr.select { |v| v != false && !v.nil? }
Cfiltered = arr.select { |v| v }
Dfiltered = arr.reject { |v| !v }
Step-by-Step Solution
Solution:
  1. Step 1: Recall Ruby truthy/falsy rules

    Only false and nil are falsy; all other values are truthy.
  2. Step 2: Understand select with block

    select { |v| v } keeps elements where v is truthy.
  3. Step 3: Analyze options

    filtered = arr.select { |v| v } directly selects truthy values; others are more verbose or incorrect.
  4. Final Answer:

    filtered = arr.select { |v| v } -> Option C
  5. Quick Check:

    Test with falsy values filtered out [OK]
Quick Trick: Use select { |v| v } to keep only truthy values [OK]
Common Mistakes:
MISTAKES
  • Using reject incorrectly
  • Overcomplicating condition with explicit false/nil checks
  • Using negation incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes