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.
But if you define a variable in a block, it is defined in the local scope and is no longer visible outside the block.

#Ruby #Condition #ControlExpressions #If #Block #VariableDefenition #VariableScope

Ruby automatically creates a variable and assigns it nil only for conditional statements.
There's also a great article (https://radan.dev/articles/ruby-local-variables) that attempts to create a local variable in a conditional statement.
You can also read a good explanation of why this happens here (https://stackoverflow.com/questions/12928050/why-does-ruby-seem-to-hoist-variable-declarations-from-inside-a-case-statement-e).
So be careful and assign a value to the new variable before the block.
Is it possible to conditionally define a local variable in Ruby?

Let’s say you wish to conditionally define a local variable in Ruby. Why would you need that? That’s beside the point, it’s mostly a thought excercise that’s an excuse to learn about a specific corner of Ruby. But, if you still want a real use case, you’re being a bit difficult, but let’s say that you’ve got some metaprogramming code that at some points uses defined?(x) calls to do something based on whether a local variable is defined or not. Yes, it’s very contrived.

Radan Skorić’s website