Bird
Raised Fist0
Rubyprogramming~10 mins

Block given? check in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Block given? check
Method called
↓
Check if block given?
↓
Yield block
↓
Continue method
↓
End
The method checks if a block is given. If yes, it runs the block with yield; if no, it skips yield and continues.
Execution Sample
Ruby
def greet
  if block_given?
    yield
  else
    puts "No block given"
  end
end

greet { puts "Hello!" }
This code runs a method that prints 'Hello!' if a block is given, otherwise prints 'No block given'.
Execution Table
StepActionblock_given? checkBranch TakenOutput
1Call greet with blocktrueYes (yield block)Hello!
2Yield block execution--Hello! printed
3Method ends---
💡 Block was given, so yield executed and method ended.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
block_given?falsetruetruetrue
Key Moments - 2 Insights
Why does the method not print 'No block given' when a block is passed?
Because block_given? returns true (see execution_table step 1), so the method yields to the block instead of printing the else message.
What happens if we call greet without a block?
block_given? returns false, so the else branch runs and prints 'No block given' (not shown in this trace but implied).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of block_given? at step 1?
Afalse
Btrue
Cnil
Dundefined
💡 Hint
Check the 'block_given? check' column in execution_table row for step 1.
At which step does the method yield to the block?
AStep 2
BStep 3
CStep 1
DNo yield occurs
💡 Hint
Look at the 'Action' and 'Branch Taken' columns in execution_table.
If greet is called without a block, what would change in the execution_table?
Ablock_given? would be true and yield runs
BMethod would raise an error
Cblock_given? would be false and else branch runs
DOutput would be 'Hello!'
💡 Hint
Refer to key_moments about behavior when no block is given.
Concept Snapshot
Use block_given? inside a method to check if a block was passed.
If true, use yield to run the block.
If false, skip yield or run alternative code.
Prevents errors when yield is called without a block.
Syntax:
  if block_given?
    yield
  else
    # no block code
  end
Full Transcript
This example shows how Ruby methods can check if a block is given using block_given?. When the method greet is called with a block, block_given? returns true, so the method yields to the block and prints 'Hello!'. If no block is given, block_given? returns false and the method prints 'No block given'. This prevents errors from calling yield without a block. The execution table traces each step: calling the method, checking block_given?, yielding the block, and ending the method. The variable tracker shows block_given? changing from false to true when the block is present. Key moments clarify why the else branch is skipped when a block exists and what happens if no block is passed. The quiz tests understanding of block_given? values, when yield runs, and behavior without a block. The snapshot summarizes how to safely use yield with block_given? in Ruby methods.

Practice

(1/5)
1. What does the Ruby method block_given? check inside a method?
easy
A. If the method is defined inside a class
B. If the method has any parameters
C. If the method returns a value
D. If a block was passed to the method

Solution

  1. Step 1: Understand the purpose of block_given?

    This method returns true if the current method was called with a block passed to it.
  2. Step 2: Differentiate from other method checks

    It does not check parameters, return values, or class definitions, only the presence of a block.
  3. Final Answer:

    If a block was passed to the method -> Option D
  4. Quick Check:

    block_given? checks block presence = A [OK]
Hint: block_given? tells if a block is passed to method [OK]
Common Mistakes:
  • Confusing block_given? with method parameters
  • Thinking it checks return values
  • Assuming it checks class membership
2. Which of the following is the correct syntax to check if a block was given inside a Ruby method?
easy
A. if block_given then yield end
B. if block_given? () yield end
C. if block_given? then yield end
D. if block_given? yield () end

Solution

  1. Step 1: Identify correct method call syntax

    block_given? is a method and should be called with a question mark and optionally parentheses. The most common and clear syntax is block_given? without parentheses.
  2. Step 2: Confirm correct use of yield

    The yield keyword runs the block if it exists. The syntax if block_given? then yield end is correct and clear.
  3. Final Answer:

    if block_given? then yield end -> Option C
  4. Quick Check:

    Correct syntax uses block_given? and yield [OK]
Hint: Use block_given? with question mark and yield inside if [OK]
Common Mistakes:
  • Omitting question mark in block_given?
  • Using block_given without parentheses incorrectly
  • Calling yield with parentheses unnecessarily
3. What will be the output of this Ruby code?
def greet
  if block_given?
    yield
  else
    puts "Hello!"
  end
end

greet { puts "Hi there!" }
greet
medium
A. Hi there!\nHello!
B. Hello!\nHello!
C. Hi there!\nHi there!
D. No output

Solution

  1. Step 1: Analyze first greet call with block

    The first call passes a block that prints "Hi there!". Since block_given? is true, yield runs the block, printing "Hi there!".
  2. Step 2: Analyze second greet call without block

    The second call has no block, so block_given? is false and the else branch runs, printing "Hello!".
  3. Final Answer:

    Hi there!\nHello! -> Option A
  4. Quick Check:

    Block runs first, then default message = A [OK]
Hint: Block runs if given; else default runs [OK]
Common Mistakes:
  • Assuming yield runs even without block
  • Thinking both calls print the same message
  • Confusing order of outputs
4. Identify the error in this Ruby method:
def show
  yield if block_given
end

show { puts "Hello!" }
medium
A. Missing question mark in block_given method call
B. yield cannot be used without arguments
C. Method show requires a parameter
D. Block cannot be passed to show method

Solution

  1. Step 1: Check block_given usage

    The method block_given? requires the question mark and should be called as block_given? or block_given?(). Here it is missing the question mark.
  2. Step 2: Confirm yield usage

    The yield is correctly used and does not require arguments here. The method does not require parameters to accept a block.
  3. Final Answer:

    Missing question mark in block_given method call -> Option A
  4. Quick Check:

    block_given? needs question mark [OK]
Hint: Always use block_given? with question mark [OK]
Common Mistakes:
  • Omitting question mark in block_given
  • Thinking yield needs arguments always
  • Assuming method needs parameters for blocks
5. You want to write a Ruby method process_items that takes an array and optionally a block. If a block is given, it should yield each item to the block; otherwise, it should return the array unchanged. Which code correctly implements this behavior?
hard
A. def process_items(arr) arr.each { |item| yield item if block_given? } end
B. def process_items(arr) if block_given? arr.each { |item| yield item } else arr end end
C. def process_items(arr) if block_given arr.each { |item| yield item } else arr end end
D. def process_items(arr) arr.each { |item| yield item } end

Solution

  1. Step 1: Check block presence correctly

    def process_items(arr) if block_given? arr.each { |item| yield item } else arr end end uses block_given? correctly to check if a block is passed before yielding.
  2. Step 2: Handle both cases properly

    If a block is given, it yields each item; otherwise, it returns the original array unchanged, matching the requirement.
  3. Step 3: Review other options for errors

    def process_items(arr) arr.each { |item| yield item } end always yields without checking block presence, causing error if no block given. def process_items(arr) if block_given arr.each { |item| yield item } else arr end end misses question mark in block_given. def process_items(arr) arr.each { |item| yield item if block_given? } end yields conditionally inside each, but block_given? inside the each block always returns false so no yielding occurs, though it returns the array.
  4. Final Answer:

    def process_items(arr) if block_given? arr.each { |item| yield item } else arr end end -> Option B
  5. Quick Check:

    Check block_given? before yield and return array if no block [OK]
Hint: Check block_given? before yield; else return array [OK]
Common Mistakes:
  • Not checking block_given? before yield
  • Missing question mark in block_given
  • Returning nil instead of array when no block
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard