Startup hacks and engineering miracles from your exhausted friends at Faraday

Antipattern: Ruby's ENV[]

Seamus Abshere on

This is part of our antipatterns series. Ouch!

Ask yourself why you're not using Hash#fetch (aka one weirdi trickito avoid the hated Ruby error NoMethodError: undefined method '[]' for nil:NilClass.)

Use Hash#fetch, not Hash#[], if you expect the value to exist.

#> params = {}

#> params['really']['important']
NoMethodError: undefined method `[]' for nil:NilClass  
# ^ barf

#> params.fetch('really').fetch('important')
KeyError: key not found: "really"  
# ^ the problem is immediately obvious

The Twelve-Factor App has us all using environment variables. But most of us default to ENV#[] to look stuff up... even if it's critical:

#> ENV['REALLY_IMPORTANT'] == 'thing'
=> false # well...

#> ENV.fetch('REALLY_IMPORTANT') == 'thing'
KeyError: key not found: "REALLY_IMPORTANT"