Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

ENV.fetch

ENV.fetch(name) → value
ENV.fetch(name, default) → value
ENV.fetch(name) { |name| block } → value

If name is the name of an environment variable, returns its value:

Example
ENV['foo'] = '0'
ENV.fetch('foo') # => '0'

Otherwise if a block is given (but not a default value), yields name to the block and returns the block’s return value:

Example
ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string

Otherwise if a default value is given (but not a block), returns the default value:

Example
ENV.delete('foo')
ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string

If the environment variable does not exist and both default and block are given, issues a warning (“warning: block supersedes default value argument”), yields name to the block, and returns the block’s return value:

Example
ENV.fetch('foo', :default) { |name| :block_return } # => :block_return

Raises KeyError if name is valid, but not found, and neither default value nor block is given:

Example
ENV.fetch('foo') # Raises KeyError (key not found: "foo")

Raises an exception if name is invalid. See Invalid Names and Values.

See also .except .fetch_values .empty? .filter also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0