What is the ENV.reject{} method in Ruby?
Overview
In Ruby, the reject{} method gives us access to the name and value of each environment variable as a 2-element array. It returns a Hash containing a value pair of environment variables that is determined by its block. If the block returns true, the value pair is added to the Hash returned. Otherwise, it ignores the pair.
Syntax
ENV.reject{|name, value| block}
Syntax for reject{} method
Parameters
name: This represents the name of each environment variable.
value: This is the value of the environment variable.
block: This is a condition that returns true or false for the name and value pair, depending on what is specified.
Return value
The value returned is a Hash of the value pair.
Example
# clear default environment variables]ENV.clear# create some new environment variablesENV["foo"] = "one"ENV["bar"] = "two"ENV["bar_code"] = "123abc"ENV["secret_code"] = "cba321"# reject name/value pair that starts with "b"puts ENV.reject { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
Explanation
- Line 2: We clear the environment variables present.
- Line 5–8: We create some new environment variables.
- Line 11: We use the
reject{}method to reject the names of environment variables that start with"b", meaning they were not added to the Hash returned. Next, we print thevaluepairs added to the Hash.