Ruby - Return early on missing ENV variables

21 Feb 2016

Here’s a quick way to bail out of a method or initializer when a required ENV variable is missing and provide a useful error message.

required_vars = %w(FOO BAR BAZ QUUX)
missing_vars = required_vars - ENV.keys
raise"The following ENV variables are required: #{missing_vars}") if missing_vars.any?

Using Ruby Array’s built-in subtract method, we get the difference between the list of variables we require and those set.

You can use this to guard against missing options in methods, too.