Variable Scope Flashcards
block
A block is a piece of code that follows a method’s invocation, delimited by either curly braces {} or do/end:
total = 0
[1, 2, 3].each { |number| total += number }
puts total # 6
total = 0 [1, 2, 3].each do |number| total += number end puts total # 6
arr = [1, 2, 3]
for i in arr do
a = 5 # a is initialized here
end
puts a # is it accessible here?
yes. The reason is because the for…do/end code did not create a new inner scope, since for is part of Ruby language and not a method invocation. When we use each, times and other method invocations, followed by {} or do/end, that’s when a new block is created.
scope
A variable’s scope determines where in a program a variable is available for use. A variable’s scope is defined by where the variable is initialized or created. In Ruby, variable scope is defined by a method definition or by a block.
method
think of methods as pieces of reusable code that your program can execute many times during it’s run. Method definitions look like this:
name = ‘Somebody Else’
def print_full_name(first_name, last_name)
name = first_name + ‘ ‘ + last_name
puts name
end
Which have self-contained scope and what does it mean?
Methods. That means that only variables initialized within the method’s body can be referenced or modified from within the method’s body. Additionally, variables initialized inside a method’s body aren’t available outside the method’s body. It’s a bit like an impenetrable bubble.