Bird
0
0

Given the array [1, 2, 3, 4], which block syntax correctly filters even numbers and returns them as a new array?

hard📝 Application Q15 of 15
Ruby - Blocks, Procs, and Lambdas
Given the array [1, 2, 3, 4], which block syntax correctly filters even numbers and returns them as a new array?
A[1, 2, 3, 4].select { |n| n.even? }
B[1, 2, 3, 4].select do |n| n.even?
C[1, 2, 3, 4].select { n.even? }
D[1, 2, 3, 4].select do n.even? end
Step-by-Step Solution
Solution:
  1. Step 1: Understand the select method and block parameters

    select filters elements for which the block returns true. The block must receive each element as a parameter.
  2. Step 2: Check syntax correctness

    [1, 2, 3, 4].select { |n| n.even? } correctly uses curly braces with block parameter |n| and calls n.even?. [1, 2, 3, 4].select do |n| n.even? has a syntax error (missing end). [1, 2, 3, 4].select { n.even? } misses block parameters. [1, 2, 3, 4].select do n.even? end misses pipes around parameter.
  3. Final Answer:

    [1, 2, 3, 4].select { |n| n.even? } -> Option A
  4. Quick Check:

    Curly braces with pipes for single-line filter [OK]
Quick Trick: Use { |var| condition } for concise filtering blocks [OK]
Common Mistakes:
  • Omitting block parameters
  • Mixing do..end without pipes for parameters
  • Using incorrect block syntax causing errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes