liveBook · Manning

Filtering

As explained in The Well-Grounded Rubyist, Fourth Edition

Filtering is the technique of selecting elements from a collection that satisfy specified criteria.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains iterator blocks, result shapes, case equality, regular-expression matching, validation, and normalization without exhaustive API reference.
Examples
Uses unpaid registrants, even numbers, ticket prices, travel dates, and country strings matched or transformed with grep.
What it assumes
Assumes Ruby blocks and enumerable objects while teaching selection criteria, regular-expression matching, and case equality through examples.
What you can do after
Apply it via Enumerable methods, regular expressions, and setter methods to select, reject, validate, normalize, or transform values.
How it connects
Connects Enumerable, iterators, find, select, grep, regular expressions, case equality, validation, and normalization.

Also explained in

Compare how 33 books explain filtering →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.