Bird
0
0

Given a list of values [1, nil, 3, nil, 5], which Ruby code correctly counts how many elements are nil?

hard📝 Application Q15 of 15
Ruby - Variables and Data Types
Given a list of values [1, nil, 3, nil, 5], which Ruby code correctly counts how many elements are nil?
AAll of the above
B[1, nil, 3, nil, 5].select(&:nil?).length
C[1, nil, 3, nil, 5].count(nil)
D[1, nil, 3, nil, 5].filter { |v| v.nil? }.size
Step-by-Step Solution
Solution:
  1. Step 1: Understand ways to count nil elements

    Ruby arrays have multiple ways to count elements matching a condition: .count(nil), .select(&:nil?).length, and .filter { |v| v.nil? }.size all work.
  2. Step 2: Verify each option

    [1, nil, 3, nil, 5].count(nil) counts elements equal to nil directly. Options B and D select elements where v.nil? is true and count them. All produce the same result.
  3. Final Answer:

    All of the above -> Option A
  4. Quick Check:

    Multiple Ruby methods count nil elements correctly [OK]
Quick Trick: Use count(nil) or select/filter with .nil? to count nils [OK]
Common Mistakes:
  • Using count without argument
  • Confusing length and size methods
  • Forgetting & before :nil? in select

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes