0
0
Rubyprogramming~5 mins

Yield to execute blocks in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ARaises an error always
BReturns the method immediately
CDefines a new block
DRuns the block passed to the method
How do you write a block when calling a method in Ruby?
AUsing <code>{ ... }</code> or <code>do ... end</code> after the method call
BInside parentheses after the method name
CUsing square brackets <code>[ ... ]</code>
DBlocks are not allowed in Ruby
What method checks if a block was given to a Ruby method?
Ayield?
Bblock_given?
Chas_block?
Dblock?
What error occurs if yield is called without a block?
ASyntaxError
BNoMethodError
CLocalJumpError
DArgumentError
Which is a correct way to use yield in a method?
Adef example; yield; end
Bdef example; yield?; end
Cdef example; yield(); end
Ddef example; yield block; end
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.