0
0
Rubyprogramming~20 mins

Yield to execute blocks in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Yield 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 yield?
Consider the following Ruby method that uses yield. What will be printed when this code runs?
Ruby
def greet
  puts "Hello"
  yield if block_given?
  puts "Goodbye"
end

greet { puts "How are you?" }
AHello\nHow are you?\nGoodbye
BHello\nGoodbye\nHow are you?
CHow are you?\nHello\nGoodbye
DHello\nGoodbye
Attempts:
2 left
💡 Hint
Remember that yield runs the block passed to the method exactly where it appears.
🧠 Conceptual
intermediate
1:30remaining
What does block_given? check in Ruby?
In Ruby, inside a method, what does the method block_given? return?
ATrue if a block was passed to the method, false otherwise
BTrue if the method has a yield statement, false otherwise
CTrue if the method returns a value, false otherwise
DTrue if the method is called with parentheses, false otherwise
Attempts:
2 left
💡 Hint
Think about how Ruby methods detect if a block was passed.
🔧 Debug
advanced
2:00remaining
Why does this Ruby code raise an error?
Look at this Ruby method and its call. Why does it raise a LocalJumpError?
Ruby
def run_block
  yield
  yield
end

run_block
AThe method tries to yield twice, which is not allowed
BNo block was given when calling <code>run_block</code>, so yield has nothing to execute
CThe method is missing a return statement
DThe block passed returns nil, causing an error
Attempts:
2 left
💡 Hint
What happens if you call yield but no block is given?
📝 Syntax
advanced
1:30remaining
Which option correctly defines a method that yields to a block with a parameter?
You want to define a Ruby method that yields a value to a block. Which code is correct?
A
def example
  yield(10))
end
B
def example
  yield(10
end
C
def example
  yield 10 do
end
D
def example
  yield 10
end
Attempts:
2 left
💡 Hint
Check for correct parentheses and syntax around yield.
🚀 Application
expert
2:30remaining
What is the output of this Ruby code using yield with multiple yields and parameters?
Analyze this Ruby code and select the exact output it produces.
Ruby
def multi_yield
  yield(1)
  yield(2)
  yield(3)
end

result = []
multi_yield { |x| result << x * 2 }
puts result.join(",")
A3,6,9
B1,2,3
C2,4,6
DError: undefined method << for nil:NilClass
Attempts:
2 left
💡 Hint
The block doubles each yielded value and appends it to the array.