liveBook · Manning

Reject

As explained in The Well-Grounded Rubyist, Fourth Edition

reject is a Ruby Hash and Enumerable method that returns a new collection containing elements for which a supplied block returns a falsy value.

Ruby’s reject method filters a collection by running a block for each element. It returns a new collection containing elements for which the block does not return true. For an array, the result is an array; for a hash, key/value pairs whose block result is true are excluded and the result remains a hash. section 9.3.5 section 10.3.2

Rejecting array elements

a = [1,2,3,4,5,6,7,8,9,10] a.reject { |item| item > 5 } # => [1, 2, 3, 4, 5] The block identifies elements to remove, so reject keeps every element that fails that test. This complements select, which keeps elements for which the block returns true. section 10.3.2

Rejecting hash pairs

h = {1 => 2, 3 => 4, 5 => 6} h.reject { |k, v| k > 1 } # => {1 => 2} Hash#reject yields each key and value to the block. The non-bang method leaves h unchanged and returns a new hash. section 9.3.5

Use reject! when the collection should be changed in place. Hashes also provide delete_if when an in-place operation should return the original hash even if no element changes. Enumerable selection generally returns arrays, but hashes retain hash results as enhanced behavior. section 9.3.5 section 10.3.1

Rejecting from introspection results

string = "Test string" methods = string.methods bangs = string.methods.grep(/.!/) unmatched = bangs.reject do |name| methods.include?(name[0..-2].to_sym) end Here reject removes bang-method names that have a corresponding non-bang method, leaving only unmatched names for the later test. section 15.2.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains block selection, result-container differences, and mutation variants, but does not descend into Enumerable implementation internals.
Examples
Uses numeric arrays, key/value hashes, and method-name introspection to demonstrate filtering and related operations.
What it assumes
Assumes familiarity with Ruby blocks and collections while reinforcing iteration, predicates, hashes, arrays, and method results.
What you can do after
Apply reject to retain elements failing a predicate, choose reject! for mutation, and distinguish array from hash results.
How it connects
Contrasts with select and find_all, and connects to Enumerable, Hash, arrays, blocks, bang methods, and object introspection.

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.