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

ENV.assoc(name) → [name, value] or nil

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)
See also .[]= .clear .[] .clone also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0