0
0
Rubyprogramming~20 mins

Rescue modifier (inline form) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Rescue Modifier Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A0
BInfinity
Cerror
DZeroDivisionError
Attempts:
2 left
💡 Hint
The rescue modifier catches exceptions and returns the rescue value instead.
Predict Output
intermediate
2: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 message
Ruby
def greet(name)
  "Hello, #{name}!"
end

message = greet(nil) rescue "No greeting"
puts message
AHello, nil!
BNo greeting
CTypeError
DHello, !
Attempts:
2 left
💡 Hint
Passing nil to string interpolation does not raise an error.
Predict Output
advanced
2: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
ASyntaxError
B3
Cfail
Drescued
Attempts:
2 left
💡 Hint
The raise happens after 1 + 2, triggering rescue.
Predict Output
advanced
2: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?
Atrue
Bfalse
Cerror
DNoMethodError
Attempts:
2 left
💡 Hint
No exception is raised, so rescue is not triggered.
Predict Output
expert
3: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 result
Ruby
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
ANoMethodError
Brescued
Cnil
DEmpty
Attempts:
2 left
💡 Hint
unwrap raises if @value is nil, rescue catches it.