This tutorial will illustrate how to filter the results from an array using the select, find and reject methods.
Using the Select Method
We use the select statement to filter elements in an array for a subset that matches specific criteria.
The select method returns a new array with all the values where the condition evaluates to true.
The select method accepts a block to specify the condition.
For example:
"React",
"Angular",
"Vue JS",
"Svelte"
]
print frameworks.select {|i| i.length > 6}
In the example above, we use the select method to filter out the string with a length greater than 6.
The code in the block will iterate over each item in the array, checking the condition. If true, then the select statement will add it to a new collection.
In-place Select
The select statement does not affect the original array. It creates a new array with items that match the specified condition.
To affect the original array in place, we can use the select! Method.
"React",
"Angular",
"Vue JS",
"Svelte"
]
frameworks.select! {|i| i.length > 6}
print frameworks
The frameworks array is modified to contain only the elements with a length greater than 6.
Using the Find Method
We can use the find method to find a single element in the array that matches a specific condition.
For example:
"React",
"Angular",
"Vue JS",
"Svelte"
]
print frameworks.find {|i| i.length == 5}
The find method will return the first match of the specified condition.
Here is an example output:
If there is no match, the method returns nil.
Sometimes you may come across the find_all method. The find_all method returns all the matches instead of a single object. You can consider it an alias of the select method.
Using The Reject Method
The reject method is the exact opposite of the select method. Instead of including the values that match a specific condition, the method rejects the elements.
For example:
"React",
"Angular",
"Vue JS",
"Svelte"
]
print frameworks.reject {|i| i.length > 6}
In the above example, we remove all the elements with a length greater than 6. In our example, this is just a single object.
The resulting value is as:
To summarize
You have just learned how to filter the elements in an array using the select, find and reject methods.
Remember: Practice equals mastery