rubyrescue

Does Ruby's $! hold value only in rescue block?


begin
  raise 'foo'
rescue
  puts $!.inspect # => #<RuntimeError: foo>
ensure
  puts $!.inspect # => nil
end
puts $!.inspect # => nil

Googled around but didn't find a clear answer.

Just want to confirm the life-time(?) of $!, does it hold value only inside a rescue block?


Solution

  • $! has the error in the rescue block, or in the the ensure block if there's no rescue block:

    begin
      raise 'foo'
    ensure
      puts $!.inspect # => #<RuntimeError: foo>
    end
    

    $! has the value nil everywhere else.