Here’s the latest bit of Ruby that had me scratching my head for a minute…

Say you have a method that takes a block of code, and this block of code is executed using yield inside of the method:

def foo
  yield
end

foo { puts "boobs"}

Now let’s say that block needs to access some variable defined inside of that method:

def foo
  n = 'boobs'
  yield
end

foo { puts "n: #{n}"}

This doesn’t work, you end up with “undefined local variable or method `n’ for main:Object (NameError)”. But if n is defined right before the call to method foo it works:

def foo
  n = 'boobs'
  yield
end

n = 'titties'
foo { puts "n: #{n}"}

This, as expected, will output “n: titties”. So how can you use n from within the method inside of the block? Like so:

def foo
  n = 'boobs'
  yield n
end

n = 'titties'
foo { |n| puts "n: #{n}"}

The result of running this code is “n: boobs”. You give the variable n as an argument to yield, and add “|n|” to the beginning of the block. At times blocks still feel foreign to me, but I think I’m starting to get the hang of them.