Ruby | Enumerable grep() function

The grep() of enumerable is an inbuilt method in Ruby returns an array of elements which contain every (element == pattern), of all the elements in the pattern. If the optional block is not given, then it returns an array containing the elements in that pattern.

Syntax: enu.grep(pattern) { |obj| block }

Parameters: The function takes a pattern and an optional block.



Return Value: It returns either an array of boolean values or an array containing the elements that are contained in the enumerable.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for grep method in Enumerable
  
# Initialize 
enu = (1..10)
  
# Prints
enu.grep (3..5)

chevron_right


Output:

[3, 4, 5]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for grep method in Enumerable
  
# Initialize 
enu = (1..10)
  
# Prints
enu.grep (3..5) { |obj| obj % 2 == 1 }

chevron_right


Output:

[true, false, true]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.