End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
class method
ENV.assoc
ENV.assoc(name) → [name, value] or nil
hash.c
View on GitHub ↗
static VALUE
env_assoc(VALUE env, VALUE key)
{
const char *s = env_name(key);
VALUE e = getenv_with_lock(s);
if (!NIL_P(e)) {
return rb_assoc_new(key, e);
}
else {
return Qnil;
}
}
Returns a 2-element Array containing the name and value of the environment variable for name if it exists:
Example
ENV.replace('foo' => '0', 'bar' => '1') ENV.assoc('foo') # => ['foo', '0']
Returns nil if name is a valid String and there is no such environment variable.
Returns nil if name is the empty String or is a String containing character '='.
Raises an exception if name is a String containing the NUL character "\0":
Example
ENV.assoc("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
Raises an exception if name has an encoding that is not ASCII-compatible:
Example
ENV.assoc("\xa1\xa1".force_encoding(Encoding::UTF_16LE)) # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
Raises an exception if name is not a String:
Example
ENV.assoc(Object.new) # TypeError (no implicit conversion of Object into String)