Block Scope

...or, how closures break encapsulation (in a good way)

Blocks see the variables of their definer, not their caller

Example of Block Scope

def twice
  yield
  yield
end

def flatter
  message = "you are great"
  twice do
    puts "#{message}!"
  end
end

message is in the scope of flatter, not twice

locals, function parameters, block parameters

def twice_with word
  yield word
  yield word.upcase
end

def flatter person
  message = "you are great"
  twice_with(person) do |name|
    puts "#{message}, #{name}!"
  end
end

flatter "Alex"

Q: Which variables are available inside the block?

Nested Scopes

With Great Power Comes Great Responsibility

 Previous Lesson Next Lesson 

Outline

[menu]

/