Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
ENV.key
ENV.key(value) → name or nil
hash.c
View on GitHub ↗
static VALUE
env_key(VALUE dmy, VALUE value)
{
StringValue(value);
VALUE str = Qnil;
rb_encoding *enc = env_encoding();
ENV_LOCKING() {
char **env = GET_ENVIRON(environ);
while (*env) {
char *s = strchr(*env, '=');
if (s++) {
rb_len_t len = strlen(s);
if (RSTRING_LEN(value) == len && strncmp(s, RSTRING_PTR(value), len) == 0) {
str = env_str_new(*env, s-*env-1, enc);
break;
}
}
env++;
}
FREE_ENVIRON(environ);
}
return str;
}
Returns the name of the first environment variable with value, if it exists:
Example
ENV.replace('foo' => '0', 'bar' => '0') ENV.key('0') # => "foo"
The order in which environment variables are examined is OS-dependent. See About Ordering.
Returns nil if there is no such value.
Raises an exception if value is invalid:
Example
ENV.key(Object.new) # raises TypeError (no implicit conversion of Object into String)