Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#grep

grep(pattern) → array
grep(pattern) {|element| ... } → array

Returns an array of objects based elements of self that match the given pattern.

With no block given, returns an array containing each element for which pattern === element is true:

Example
a = ['foo', 'bar', 'car', 'moo']
a.grep(/ar/)                   # => ["bar", "car"]
(1..10).grep(3..8)             # => [3, 4, 5, 6, 7, 8]
['a', 'b', 0, 1].grep(Integer) # => [0, 1]

With a block given, calls the block with each matching element and returns an array containing each object returned by the block:

Example
a = ['foo', 'bar', 'car', 'moo']
a.grep(/ar/) {|element| element.upcase } # => ["BAR", "CAR"]

Related: grep_v.

See also #flat_map #grep_v #first #group_by also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0