Ruby has a peculiarity: when you define a variable in a conditional expression (if / unless / case / :? (ternary if)), it becomes visible from then on.
It’s as if it was assigned nil before the conditional expression, and you don’t need to explicitly declare it:
a = nil # in this case it is unnecessary
if true
a = 42
end
puts a.inspect # 42
But if you define a variable in a block, it is defined in the local scope and is no longer visible outside the block, for example:
a = nil # you will get an error: "undefined local variable or method 'a' for main (NameError)"
# if you do not assign nil to the variable a
%w[r u b y].each do
a = 42
end
puts a.inspect
Ruby automatically creates a variable and assigns it nil only for conditional statements. There’s also a great article that attempts to create a local variable in a conditional statement. You can also read a good explanation of why this happens here. So be careful and assign a value to the new variable before the block.