What is the select{} method of the ENV class in Ruby?
Overview
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.
Syntax
ENV.select{|name, value| block}
Syntax for select{} method
Parameters
name: The name of each environment variable.
value: The value of each environment variable.
block: This is a condition. It takesnameandvaluein a form of the two-elements array as parameters.
Return value
The value returned is a hash of name-value pairs.
Code Example
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") }
Explanation
In the code above,
- Line 2: We clear the default or environment variables present.
- Lines 5 to 8: We create the new environment variables.
- Line 11: We use the
select{}method to select environment variables that begin with the letterb.