2 ms·
Despite using ENV all the time, this article made me actually question what the hell it actually is, i.e. how it is implemented. It quacks very muck like a Hash
by sjtgraham 12y ago
Despite using ENV all the time, this article made me actually question what the hell it actually is, i.e. how it is implemented. It quacks very muck like a Hash, so after reading this I thought all these solutions a bit ceremonious. Why not just set ENV's default proc to raise a KeyError to behave like Hash#fetch:
ENV.default_proc = ->(_,key) { raise KeyError.new "Key not found: #{key.inspect}" }
Alas, ENV is not a Hash and doesn't have default_proc. It's an instance of Object, i.e. literally Object.new, decorated with extra methods, see https://github.com/ruby/ruby/blob/d738e3e15533e0f500789faaedcef9ed9ca362b9/hash.c#L3922-3973 https://github.com/ruby/ruby/blob/d738e3e15533e0f500789faaed.... Wow, TIL.
Anyway, a real simple way to have ENV[] behave like ENV.fetch is to define a method on ENV's metaclass:
def ENV.[](key)
fetch key
end
This worked fine in irb but use fetch, intent is clearer.