Scope Notes Day 1 Flashcards
what is lexical scope?
lexical scope describes how variable names resolve if we put them in structures like methods, conditionals, or blocks.
What is local scope?
local scope is where you can reference variables only defined within the same scope.
def say_hello message = "hello" end
say_hello
p message # NameError: undefined local variable
what is global scope?
global scope is where we can define variables that are allowed to be referenced everywhere in our code regardless of local scope. Denoted using ($) “hello globe”
what is a constant?
it’s another way to declare a variable to be in the global scope. A constant is denoted syntactically by beginning the name with a capital letter. By convention we like to make the entire name capital to emphasize it being a special constant.A constant variable cannot be reassigned:
FOOD = “pho”
p FOOD # => “pho”
FOOD = "ramen" #warning: already initialized constant #warning: previous definition of FOOD was here
you can still mutate that constant name without warning:
FOOD = “pho”
FOOD[0] = “P”
p FOOD # => “Pho
what does not have its own scope?
Blocks don’t have their own scope, they are really a part of the containing method’s scope. Other structures like conditionals or while loops also don’t have their own scope, they are really part of the containing scope.