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.


2 Comments
instead of using
yield, just add the block to the parameter list using an ampersand, and then call the block as you would any anonymous function.def foo &block
input = "boobs"
block[ input ] unless block.nil?
end
n = "titties"
foo { |input| puts "input is: #{input}" }
foo { |input| puts "* 2 is: #{input * 2}" }
foo { |input| puts "reversed is: #{input.reverse}"
i’ve never had to use
yieldandblock_given?. i used the[](the synonym for blockcall) andnil?methods instead.Thank you for sharing!