0
0
Rubyprogramming~20 mins

Block syntax (do..end and curly braces) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Block Syntax Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of block with do..end vs curly braces
What is the output of the following Ruby code?
Ruby
def test_block
  yield
end

result = []
test_block do
  result << 1
end

test_block { result << 2 }

puts result.inspect
A[1, 2]
B[2, 1]
CSyntaxError
D[]
Attempts:
2 left
💡 Hint
Both do..end and curly braces can be used to pass blocks to methods.
Predict Output
intermediate
2:00remaining
Return value of block with do..end vs curly braces
What is the output of this Ruby code?
Ruby
def block_return
  result = yield
  puts result
end

block_return do
  5 + 3
end

block_return { 10 + 2 }
ASyntaxError
B
nil
nil
C
5
10
D
8
12
Attempts:
2 left
💡 Hint
The yield keyword returns the value of the block.
🔧 Debug
advanced
2:00remaining
Identify the syntax error in block usage
Which option contains a syntax error when defining a block in Ruby?
Aarray.map { |x| x * 2 }
Barray.map { |x| x * 2 end }
Carray.map do |x|; x * 2; end
Darray.map do |x| x * 2 end
Attempts:
2 left
💡 Hint
Check if the block delimiters match correctly.
🧠 Conceptual
advanced
2:00remaining
Difference in precedence between do..end and curly braces
Which statement about Ruby block syntax precedence is true?
ABoth have the same precedence
Bdo..end blocks have higher precedence than curly braces
CCurly braces have higher precedence than do..end blocks
DPrecedence depends on the method name
Attempts:
2 left
💡 Hint
Think about how Ruby parses method calls with blocks.
🚀 Application
expert
3:00remaining
Predict output with nested blocks and different syntax
What is the output of this Ruby code?
Ruby
def outer
  yield
end

outer do
  outer { puts 'Inner block' }
  puts 'Outer block'
end
A
Inner block
Outer block
BInner block
CSyntaxError
D
Outer block
Inner block
Attempts:
2 left
💡 Hint
Blocks can be nested and execute in order of yield calls.