Blocks and Methods
Blocks Yield
A Ruby method can call yield to run a block supplied by the caller.
Blocks Yield
blocks_yield.rb
def with_greeting(name)
puts "before block"
yield(name)
puts "after block"
end
name =
with_greeting(name) do |value|
puts "hello #{value}"
end
def with_greeting(name)
puts "before block"
yield(name)
puts "after block"
end
name =
with_greeting(name) do |value|
puts "hello #{value}"
end
def with_greeting(name)
puts "before block"
yield(name)
puts "after block"
end
name =
with_greeting(name) do |value|
puts "hello #{value}"
end
yield
`yield` transfers control from a method to the block passed with the method call.