Recall & Review
beginner
What does the
yield keyword do in Ruby?yield pauses the method and runs the block of code given to the method, then returns to the method.
Click to reveal answer
beginner
How do you pass a block to a method in Ruby?
You write the method call with a block using { ... } or do ... end after the method name.
Click to reveal answer
intermediate
What happens if a method calls
yield but no block is given?Ruby raises a LocalJumpError because it expects a block to run but none was provided.
Click to reveal answer
intermediate
How can you check if a block was given before calling
yield?Use the method block_given? which returns true if a block is passed, otherwise false.
Click to reveal answer
beginner
Write a simple Ruby method that uses
yield to run a block.def greet
puts "Hello"
yield
puts "Goodbye"
end
greet { puts "Nice to meet you!" }Click to reveal answer
What does
yield do inside a Ruby method?✗ Incorrect
yield runs the block given to the method at that point.
How do you write a block when calling a method in Ruby?
✗ Incorrect
Blocks are written after the method call using curly braces or do-end.
What method checks if a block was given to a Ruby method?
✗ Incorrect
block_given? returns true if a block was passed.
What error occurs if
yield is called without a block?✗ Incorrect
Ruby raises LocalJumpError when yield has no block.
Which is a correct way to use
yield in a method?✗ Incorrect
yield is called simply as yield inside the method.
Explain how
yield works in Ruby methods and why it is useful.Think about how a method can run extra code given from outside.
You got /4 concepts.
Describe how to safely use
yield when a block might not be given.How to prevent errors if no block is passed?
You got /3 concepts.