0
0
Rubyprogramming~20 mins

Proc creation and call in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Proc Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a Proc call with arguments
What is the output of this Ruby code when the proc is called?
Ruby
my_proc = Proc.new { |x, y| x * y }
result = my_proc.call(3, 4)
puts result
Anil
B12
C7
DError: wrong number of arguments
Attempts:
2 left
💡 Hint
Remember that Proc.new creates a block that can take arguments and returns the last expression.
Predict Output
intermediate
2:00remaining
Proc with missing arguments
What happens when this proc is called with fewer arguments than expected?
Ruby
my_proc = Proc.new { |x, y| x + (y || 0) }
puts my_proc.call(5)
A5
BError: wrong number of arguments
Cnil
D0
Attempts:
2 left
💡 Hint
Procs allow missing arguments and assign nil if not provided.
Predict Output
advanced
2:00remaining
Difference between Proc and lambda call behavior
What is the output of this code?
Ruby
my_lambda = ->(x, y) { x / y }
my_proc = Proc.new { |x, y| x / y }
puts my_lambda.call(10, 0)
puts my_proc.call(10, 0)
AZeroDivisionError on lambda call, no output on proc call
BZeroDivisionError on lambda call, Infinity on proc call
CZeroDivisionError on lambda call, nil on proc call
DZeroDivisionError on lambda call, ZeroDivisionError on proc call
Attempts:
2 left
💡 Hint
Both lambda and proc execute the division, which raises an error when dividing by zero.
Predict Output
advanced
2:00remaining
Return behavior inside Proc vs lambda
What is the output of this Ruby code?
Ruby
def test_return
  my_proc = Proc.new { return 'proc return' }
  my_lambda = -> { return 'lambda return' }
  result_proc = my_proc.call
  result_lambda = my_lambda.call
  'method end'
end
puts test_return
Aproc return
Bmethod end
Clambda return
DError: unexpected return
Attempts:
2 left
💡 Hint
A return inside a proc returns from the enclosing method, but a return inside a lambda returns from the lambda only.
🧠 Conceptual
expert
2:00remaining
Which option causes a LocalJumpError?
Which of these code snippets will raise a LocalJumpError when executed?
A
def method
  my_proc = Proc.new { return 5 }
  my_proc.call
  10
end
puts method
B
my_lambda = -> { return 5 }
my_lambda.call
C
my_proc = Proc.new { return 5 }
my_proc.call
D
def method
  my_lambda = -> { return 5 }
  my_lambda.call
  10
end
puts method
Attempts:
2 left
💡 Hint
A return inside a proc called outside a method context causes LocalJumpError.