We can use the select{}
method to select some environment variables based on a condition specified in the block
. This method takes a block that specifies the condition. For every name
and value
pair that returns true by the condition, they are added to a Hash returned by this method.
ENV.select{|name, value| block}
name
: The name of each environment variable.value
: The value of each environment variable.block
: This is a condition. It takes name
and value
in a form of the two-elements array as parameters. The value returned is a hash of name-value pairs.
Let's look at the code below:
# clear default environment variablesENV.clear# create new environment variablesENV["token"] = "12345"ENV["base_url"] = "https://baseurl.com"ENV["foo"] = "0"ENV["bar"] = "1"# select variables that starts with "b"puts ENV.select{|name, value| name.start_with?("b") }
In the code above,
select{}
method to select environment variables that begin with the letter b
.