Filtering selects elements from a collection when they satisfy specified criteria. In Ruby, Enumerable filtering methods are iterators: a block supplies the inclusion or exclusion test. Depending on the method and matches, the result can be one object, an array, or nil. section 10.3
Ruby provides several filtering patterns:
- Use find for a one-object search, such as locating the first unpaid conference registrant or another element meeting a criterion. section 10.3
- Use select for a multiple-object result set when the block explicitly defines which elements belong in the result. section 10.3
- Use grep for concise filtering based on case equality; with a regular expression, it selects matching strings. section 11.7.4
- Use setter methods as gatekeepers to reject malformed values or normalize accepted data before storing it. section 3.3.3
Filtering strings with grep
Given ["USA", "UK", "France", "Germany"], grep(/[a-z]/) returns ["France", "Germany"]. The equivalent select form is more verbose: select { |c| /[a-z]/ === c }. Supplying a block to grep also maps the selected values, producing ["FRANCE", "GERMANY"] when each match is uppercased. section 11.7.4
>> ["USA", "UK", "France", "Germany"].grep(/[a-z]/)
=> ["France", "Germany"]
Run the grep example to see regular-expression filtering retain only the matching strings. section 11.7.4
































