def foo #bar = nil if true bar = 1 else bar = 2 end bar #<-- shouldn't this refer to nil since the bar from the if statement is removed from the stack? end puts foo # prints "1"
I always thought you had to make a temporary variable and define it as nil or an initial value so that variables defined inside an if/else statement would persist outside the scope of the if/else statement and not disappear off the stack?? Why does it print 1 and not nil?
If you define the variable inside an if statement, than it'll only be visible inside the scope of the if statement, which includes the statement itself plus child statements. You should define the variable outside the scope and then update its value inside the if statement.
Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.
No. That is not allowed in C. According to the ANSI C Grammar, the grammar for the if statement is IF '(' expression ')' statement . expression cannot resolve to declaration , so there is no way to put a declaration in an if statement like in your example.
Re: Using global variables in functions with if statements There are global and local variables. All variables declared in the first (global) namespace are global. All other variables (declared in a function) are local in the function.
Variables are local to a function, class or module defintion, a proc
, a block.
In ruby if
is an expression and the branches don't have their own scope.
Also note that whenever the parser sees a variable assignment, it will create a variable in the scope, even if that code path isn't executed:
def test if false a = 1 end puts a end test # ok, it's nil.
It's bit similar to JavaScript, though it doesn't hoist the variable to the top of the scope:
def test puts a a = 1 end test # NameError: undefined local variable or method `a' for ...
So even if what you were saying were true, it still wouldn't be nil
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With