Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Variables defined in If/else statement are accessible outside of if/else? [duplicate]

Tags:

ruby

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?

like image 477
bigpotato Avatar asked Dec 21 '14 18:12

bigpotato


People also ask

How do you use a variable outside of an IF statement?

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.

Can I define a variable inside an 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.

Can you declare variables in an if statement in C?

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.

Are variables inside if statements global?

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.


1 Answers

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.

like image 198
Karoly Horvath Avatar answered Oct 01 '22 10:10

Karoly Horvath