There is Ruby $! to hold value only in the salvage block?

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

Hid, but did not find a clear answer.

Just want to confirm the lifetime (?) $! , does it hold the value only inside the rescue block?

+5
source share
2 answers

$! has an error in the rescue unit or in the support unit if there is no rescue unit:

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

$! matters nil everywhere.

+6
source

No, the read-only variable is $! Visible and accessible anywhere and contains nil , with the exception of escape blocks.

It is also unique to each thread. This is the current exception (the English library calls it $ERROR_INFO ), and after reset to nil , if it has not been raised again, it returns to the current exception.

From a file in which there are no other lines, we see that it is really $ !.

 puts defined?($!) puts $!.inspect irb(main):001:0> defined?($!) => "global-variable" irb(main):002:0> $! => nil irb(main):003:0> 

And in the IRB we see that it is defined and see.

This is really not entirely (or rather should not be) unexpected since $ means that it is a β€œglobal variable” and as such is globally visible.

I could not find where it is not visible. Even in BasicObject, this is visible.

 irb(main):001:0> class BasicObject irb(main):002:1> def is_it_visible irb(main):003:2> defined?($!) irb(main):004:2> end irb(main):005:1> end => :is_it_visible irb(main):006:0> BasicObject.allocate.is_it_visible => "global-variable" irb(main):007:0> 
0
source

Source: https://habr.com/ru/post/1210710/


All Articles