liveBook · Manning

Select!

As explained in The Well-Grounded Rubyist, Fourth Edition

select! is a mutating collection method that removes elements failing a block-based selection test from the receiver and returns the modified collection or nil when no change occurs.

Use `select!` when a collection should keep only the elements that pass a block’s test—and the original collection should change. Arrays, hashes, and sets provide this in-place counterpart to `select` (also called `filter`). section 10.3.2

Keep selected hash pairs

`h = {1 => 2, 3 => 4, 5 => 6}` `h.select! {|key, value| key > 1 } # => {3 => 4, 5 => 6}` `h # => {3 => 4, 5 => 6}` `h.select! {|key, value| key > 1 } # => nil` The block tests each key/value pair. The first call removes a pair; the second has nothing left to remove, so it returns `nil`. section 9.3.5

The return value matters: `nil` means the selection made no change, not that it produced an empty collection. Unlike `select!`, `select` returns a separate result. For a hash operation that changes the receiver but returns that hash even when unchanged, use `keep_if`. section 9.3.5 section 10.3.2

`reject!` is the in-place counterpart for the opposite test: it removes elements for which the block returns true. There is also a `filter!` alias for `select!`, but no `find_all!` synonym. section 9.3.5 section 10.3.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains block-based filtering and in-place behavior, with a hash-specific account of the nil return when nothing changes.
Examples
Uses hash key/value selection and array filtering to distinguish retained elements from a new selection result.
What it assumes
Assumes familiarity with Ruby blocks and collections; does not teach block syntax from zero.
What you can do after
Operate/configure it to prune a Ruby collection in place and recognize a nil return when a hash remains unchanged.
How it connects
Contrasts select!, select, filter!, reject!, keep_if, and find_all.

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.