0
0
Rubyprogramming~5 mins

Block given? check in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does block_given? do in Ruby?

block_given? checks if a block was passed to the current method. It returns true if a block is present, otherwise false.

Click to reveal answer
beginner
How do you use block_given? inside a method?

Inside a method, you call block_given? to test if a block was passed. If true, you can safely call yield to execute the block.

Click to reveal answer
intermediate
What happens if you call yield without a block and don't check block_given??

Ruby raises a LocalJumpError because yield expects a block to be given. Using block_given? prevents this error by checking first.

Click to reveal answer
beginner
Example: What will this method print?<br>
def greet
  if block_given?
    yield
  else
    puts 'Hello!'
  end
end

greet

This method prints Hello! because no block is given when calling greet. The block_given? check is false, so it runs the else part.

Click to reveal answer
beginner
Why is block_given? useful in Ruby methods?

It lets methods behave differently depending on whether a block is passed. This makes methods flexible and safe by avoiding errors when no block is given.

Click to reveal answer
What does block_given? return if a block is passed to the method?
Atrue
Bfalse
Cnil
Draises an error
What Ruby keyword is used to run the block inside a method?
Arun
Bcall
Cyield
Dexecute
What error occurs if you use yield without a block and no block_given? check?
ALocalJumpError
BArgumentError
CSyntaxError
DNoMethodError
Which of these is a correct way to check if a block is given inside a method?
Aif block_passed?
Bif block_given?
Cif has_block?
Dif block?
What will this code print?<br>
def test
  if block_given?
    yield
  else
    puts 'No block'
  end
end

test { puts 'Block here' }
ANo block
BError
CNothing
DBlock here
Explain how block_given? helps avoid errors when using blocks in Ruby methods.
Think about what happens if you call yield without a block.
You got /3 concepts.
    Describe a simple Ruby method that behaves differently when a block is given versus when it is not.
    Use an example like greeting with or without a block.
    You got /3 concepts.