Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
ENV.select
ENV.select {|name, value| ... } → hash of name/value pairs
ENV.select → an_enumerator
ENV.filter {|name, value| ... } → hash of name/value pairs
ENV.filter → an_enumerator
hash.c
View on GitHub ↗
static VALUE
env_select(VALUE ehash)
{
VALUE result;
VALUE keys;
rb_len_t i;
RETURN_SIZED_ENUMERATOR(ehash, 0, 0, rb_env_size);
result = rb_hash_new();
keys = env_keys(FALSE);
for (i = 0; i < RARRAY_LEN(keys); ++i) {
VALUE key = RARRAY_AREF(keys, i);
VALUE val = rb_f_getenv(Qnil, key);
if (!NIL_P(val)) {
if (RTEST(rb_yield_values(2, key, val))) {
rb_hash_aset(result, key, val);
}
}
}
RB_GC_GUARD(keys);
return result;
}
Calls the block with each environment variable name and value, returning a Hash of the names and values for which the block returns a truthy value:
Example
ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2') ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"} ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
With no block given, returns a new Enumerator.