Bird
0
0

Given the array nums = [0, 1, 2, 3], which code snippet correctly prints only the non-zero numbers using inline unless?

hard📝 Application Q15 of 15
Ruby - Control Flow
Given the array nums = [0, 1, 2, 3], which code snippet correctly prints only the non-zero numbers using inline unless?
Anums.each { |n| puts n if n != 0 }
Bnums.each { |n| puts n if n == 0 }
Cnums.each { |n| puts n unless n != 0 }
Dnums.each { |n| puts n unless n == 0 }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want to print numbers except zero, so skip zero and print others.
  2. Step 2: Analyze each option

    nums.each { |n| puts n unless n == 0 } uses puts n unless n == 0, which prints n only if n is not zero. nums.each { |n| puts n if n == 0 } prints only zero, which is wrong. nums.each { |n| puts n unless n != 0 } prints only zero because unless n != 0 means if n == 0. nums.each { |n| puts n if n != 0 } prints non-zero numbers but uses inline if, not unless.
  3. Final Answer:

    nums.each { |n| puts n unless n == 0 } -> Option D
  4. Quick Check:

    Inline unless skips zero, prints others [OK]
Quick Trick: Use unless with condition to skip unwanted values [OK]
Common Mistakes:
MISTAKES
  • Confusing unless with if
  • Printing zero instead of skipping
  • Using wrong condition logic

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes