Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand ruby local scope

Tags:

ruby

In this example,

def foo(x)   if(x > 5)     bar = 100   end   puts bar end 

Then foo(6) Outputs: 100 and foo(3) outputs nothing.

However if i changed the definition to

def foo(x)   if(x > 5)     bar = 100   end   puts bob end 

I get an "undefined local variable or method" error.

So my question is why I am not getting this error when I call foo(3) and bar is never set?

like image 406
rebo Avatar asked Nov 11 '10 13:11

rebo


People also ask

What does Scope mean in Ruby?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

What is binding in Ruby?

To keep track of the current scope, Ruby uses bindings, which encapsulate the execution context at each position in the code. The binding method returns a Binding object which describes the bindings at the current position.


1 Answers

There a couple of things going on here. First, variables declared inside the if block have the same local scope as variables declared at the top level of the method, which is why bar is available outside the if. Second, you're getting that error because bob is being referenced straight out of the blue. The Ruby interpreter has never seen it and never seen it initialized before. It has, however, seen bar initialized before, inside the if statement. So when is gets to bar it knows it exists. Combine those two and that's your answer.

like image 162
Todd Avatar answered Sep 29 '22 15:09

Todd