Variable Scope Flashcards

1
Q

block

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

arr = [1, 2, 3]

for i in arr do
a = 5 # a is initialized here
end

puts a # is it accessible here?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

scope

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

method

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which have self-contained scope and what does it mean?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly