0
0
Rubyprogramming~20 mins

Block given? check in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Block Given Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using block_given??
Consider the following Ruby method that checks if a block is given and yields to it if so. What will be printed when calling greet with and without a block?
Ruby
def greet
  if block_given?
    yield
  else
    puts "No block given"
  end
end

greet

greet { puts "Hello from block!" }
A
No block given
No block given
B
No block given
Hello from block!
C
Hello from block!
No block given
D
Hello from block!
Hello from block!
Attempts:
2 left
💡 Hint
Remember that block_given? returns true only if a block is passed to the method.
🧠 Conceptual
intermediate
1:30remaining
What does block_given? return inside a method?
In Ruby, what does the method block_given? return when called inside a method?
ARaises an error if no block is given
BTrue if any method in the program has a block, false otherwise
CTrue if the method was called with a block, false otherwise
DAlways true, because blocks are always available
Attempts:
2 left
💡 Hint
Think about whether the method itself received a block or not.
🔧 Debug
advanced
2:00remaining
Why does this code raise an error when using yield without block_given??
Look at this Ruby method:
def run
  yield
end

run
What error will this code raise and why?
ANo error, it prints nothing
BNoMethodError because yield is not a method
CSyntaxError because yield is used incorrectly
DLocalJumpError because yield is called without a block
Attempts:
2 left
💡 Hint
What happens if you call yield but no block is given?
Predict Output
advanced
2:00remaining
What is the output of this method using block_given? and yield?
What will this Ruby code print?
def check
  if block_given?
    yield(5)
  else
    puts "No block"
  end
end

check { |x| puts x * 2 }
check
A
10
No block
B
5
No block
C
No block
10
D
No block
No block
Attempts:
2 left
💡 Hint
The block receives the number 5 and multiplies it by 2.
🧠 Conceptual
expert
2:30remaining
How does block_given? behave with nested method calls?
Given these Ruby methods:
def outer
  inner
end

def inner
  block_given?
end

result = outer { puts "Hi" }
What is the value of result after this code runs?
Afalse
Btrue
Cnil
DRaises an error
Attempts:
2 left
💡 Hint
Does the block passed to outer get passed automatically to inner?