A detail on how they work
In Ruby, local variables are created when the parser encounters them, not dynamically at runtime! Furthermore, a if
does not create a new scope, making variables accessible after the scope has ended. This is also the case for unless
, while
, until
and for
.
A more interesting example highlighting the parser step. In the 1st if
, the parser sees and creates the a
variable after the condition, which will therefore be false at runtime. In the 2nd case, it sees and creates b
before! (A if
inline is therefore not equivalent!)
Link to Ruby documentation for local variables.