Bird
0
0

Find the error in this Ruby snippet:

medium📝 Debug Q7 of 15
Ruby - Basics and Runtime
Find the error in this Ruby snippet:
arr = [1, 2, 3]
arr.each do |num|
  puts num * 2
end
puts num
ANo error, code runs fine
BSyntax error in block definition
Carr.each cannot be used with puts
Dnum is not accessible outside the block
Step-by-Step Solution
Solution:
  1. Step 1: Understand block variable scope

    Variable 'num' is local to the block and not accessible outside.
  2. Step 2: Identify error cause

    puts num outside the block causes an error because 'num' is undefined there.
  3. Final Answer:

    num is not accessible outside the block -> Option D
  4. Quick Check:

    Block variables have local scope only [OK]
Quick Trick: Block variables can't be used outside their block [OK]
Common Mistakes:
  • Using block variable outside block
  • Assuming block variables are global
  • Ignoring scope rules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes