Consider the following two snippets of ruby code.
puts "One"
if false
d = 1
end
puts "Two"
puts d
puts "Three"
This prints the following
One
Two
Three
Now, consider the following
[].each do |i|
flag = false
end
puts "Two"
puts flag
puts "Three"
This gives the following
Two
'<main>': undefined local variable or method 'flag' for main:Object (NameError)
Why is it that in the first case a blank is printed and the 2nd case an error is thrown ?
Thanks

ifon the other hand - doesn't. When the interpreter sees a line where a variable will be assigned a value, it makes sure it is defined first and initializes it withnil. That is also whyfoo = barwill give you an error, whilebaz = bazwill not.flagvariable is the scope of the block hence not visible outside (ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/localvars.html). In the first case though, the variable does get defined even if the code block has not executed - this part I am not sure about - may be Ruby interpreter marks it as defineddtonilin your first example, so no exception is raised, even though the lined=1is never executed.