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
