yield
In this page:
yield
Inside a method, yield invokes the block that was passed to it, optionally passing values into the block as arguments. block_given? checks whether a block was actually supplied before yielding, avoiding an error if a caller forgets to pass one. This is the mechanism that lets you write your own methods that behave like each or map.
Note: Always guard yield with if block_given? unless a block is strictly required, to avoid a LocalJumpError when none is passed.
Example: yield
def repeat_twice
yield
yield
end
repeat_twice { puts "Hello!" }
def with_value
if block_given?
yield(42)
else
puts "No block given"
end
end
with_value { |n| puts "Got: #{n}" }
with_value
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: