Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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/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.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: