Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between at_exit and END (upper case) in Ruby

Tags:

ruby

keyword

What differences, if any, exist between the Kernel#at_exit method and the END (all upper case) keyword? Is the latter merely a more Perlish way of doing things, and the former more Ruby-esque?

I tried doing defined?(END {puts "Bye"}), but got a syntax error.

like image 971
Andrew Grimm Avatar asked Jul 30 '12 23:07

Andrew Grimm


2 Answers

"The Ruby Programming Language" defines a minor difference in their behavior. at_exit can be called multiple times when within a loop and each iterated call will be executed when the code exits. END will only be called once when inside a loop.

...If an END statement is within a loop and is executed more than once, then the code associated with it is still only registered once:

a = 4;
if (true)
  END { # This END is executed
  puts "if"; # This code is registered
  puts a # The variable is visible; prints "4"
}
else
  END { puts "else" } # This is not executed
end
10.times {END { puts "loop" }} # Only executed once

The Kernel method at_exit provides an alternative to the END statement; it registers a block of code to be executed just before the interpreter exits. As with END blocks, the code associated with the first at_exit call will be executed last. If the at_exit method is called multiple times within a loop, then the block associated with it will be executed multiple times when the interpreter exits.

So, running:

2.times {
  END { puts 'END'}
  at_exit { puts 'at_exit' }
}

results in:

at_exit
at_exit
END
like image 104
the Tin Man Avatar answered Oct 25 '22 10:10

the Tin Man


Using END inside a method produces a warning, where at_exit doesn’t (although both still work):

def with_end
  END {puts 'with END'}
end

def with_at_exit
  at_exit {puts 'with at_exit'}
end

with_end
with_at_exit

output:

$ ruby foo.rb 
foo.rb:2: warning: END in method; use at_exit
with at_exit
with END

On a less practical level, END is a language keyword, and at_exit is a method in the language.

like image 44
matt Avatar answered Oct 25 '22 11:10

matt