Challenge - 5 Problems
Rescue Modifier Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of rescue modifier with division by zero
What is the output of this Ruby code?
result = 10 / 0 rescue "error" puts result
Ruby
result = 10 / 0 rescue "error" puts result
Attempts:
2 left
💡 Hint
The rescue modifier catches exceptions and returns the rescue value instead.
✗ Incorrect
The division by zero raises an exception, but the rescue modifier catches it and returns the string "error".
❓ Predict Output
intermediate2:00remaining
Rescue modifier with method call
What will this Ruby code print?
def greet(name)
"Hello, #{name}!"
end
message = greet(nil) rescue "No greeting"
puts messageRuby
def greet(name) "Hello, #{name}!" end message = greet(nil) rescue "No greeting" puts message
Attempts:
2 left
💡 Hint
Passing nil to string interpolation does not raise an error.
✗ Incorrect
The method returns "Hello, nil!" because #{nil} becomes "nil". No exception occurs, so rescue is not triggered.
❓ Predict Output
advanced2:00remaining
Rescue modifier with multiple expressions
What is the output of this Ruby code?
value = (1 + 2; raise 'fail') rescue 'rescued' puts value
Ruby
value = (1 + 2; raise 'fail') rescue 'rescued' puts value
Attempts:
2 left
💡 Hint
The raise happens after 1 + 2, triggering rescue.
✗ Incorrect
The expression raises an exception, so the rescue modifier returns 'rescued'.
❓ Predict Output
advanced2:00remaining
Rescue modifier with method returning nil
What will this Ruby code output?
def maybe_fail nil end result = maybe_fail rescue "error" puts result.nil?
Ruby
def maybe_fail nil end result = maybe_fail rescue "error" puts result.nil?
Attempts:
2 left
💡 Hint
No exception is raised, so rescue is not triggered.
✗ Incorrect
The method returns nil normally, so result is nil and result.nil? returns true.
❓ Predict Output
expert3:00remaining
Rescue modifier with chained method calls and exception
What is the output of this Ruby code?
class Box
def initialize(value)
@value = value
end
def unwrap
@value or raise "Empty"
end
end
box = Box.new(nil)
result = box.unwrap rescue "rescued"
puts resultRuby
class Box def initialize(value) @value = value end def unwrap @value or raise "Empty" end end box = Box.new(nil) result = box.unwrap rescue "rescued" puts result
Attempts:
2 left
💡 Hint
unwrap raises if @value is nil, rescue catches it.
✗ Incorrect
unwrap raises "Empty" because @value is nil, rescue modifier catches and returns "rescued".