Reason #20 • January 20th, 2026

Return out of files

In Ruby, the return keyword is used to exit from methods as in any other language. However, did you know that you can also use return to exit a file completely? This feature, known as "top level return", can be useful in the same way that guard statements are, avoiding unnecessary nesting and making your code more straightforward to read from top to bottom.

Example of skipping a Ruby on Rails initializer, but only in the production environment:

Ruby
# config/initializers/rswag.rb

return if Rails.env.production?

Rswag::Api.configure do |config|
  # ...
end
    

I concede that this use case is very niche. I think I've only used it in production code twice or so over the years. But there is something endearing about it. Maybe the reason I love it is because at some point, I had a feeling it would work, and I tried it and lo and behold, it did exactly what I hoped it would. So for me it embodies the principle of least astonishment.

History

Support for top-level return is a relatively new feature of Ruby, introduced in version 2.4.0 released on Christmas 2016.

Other languages with top-level return statements include PHP and Lua as well as scripting languages like Bash and PowerShell. Notably, in PHP and Lua, the return value can be captured by the file running the require statement.