Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
ENV.fetch
static VALUE
env_fetch(int argc, VALUE *argv, VALUE _)
{
VALUE key;
int block_given;
const char *nam;
VALUE env;
rb_check_arity(argc, 1, 2);
key = argv[0];
block_given = rb_block_given_p();
if (block_given && argc == 2) {
rb_warn("block supersedes default value argument");
}
nam = env_name(key);
env = getenv_with_lock(nam);
if (NIL_P(env)) {
if (block_given) return rb_yield(key);
if (argc == 1) {
rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE"\"", key), envtbl, key);
}
return argv[1];
}
return env;
}
If name is the name of an environment variable, returns its value:
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:
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:
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:
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:
ENV.fetch('foo') # Raises KeyError (key not found: "foo")
Raises an exception if name is invalid. See Invalid Names and Values.