process.env.dev

Environment Variables in Ruby

ENV[] and dotenv gem

Reading Environment Variables

Ruby exposes environment variables through the ENV hash-like object. Access variables with bracket notation or the fetch method:

ruby
db_url = ENV['DATABASE_URL']
port = ENV.fetch('PORT', '3000').to_i
api_key = ENV.fetch('API_KEY') # raises KeyError if missing

Setting Environment Variables

ruby
ENV['MY_VAR'] = 'value'
ENV.delete('MY_VAR')

Popular Libraries

dotenv (the dotenv gem) loads .env files. It is the original dotenv implementation that inspired ports to other languages. In Rails, add dotenv-railsto your Gemfile and it loads automatically.

Common Gotchas

  • All values in ENV are strings. Cast with .to_i, .to_f, etc.
  • ENV.fetch raises KeyError for missing keys — use it for required variables.
  • In Rails, use Rails.application.credentials for secrets rather than plain env vars when possible.