Ruby | Enumerable grep() function
Last Updated :
05 Dec, 2019
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:
enu = ( 1 .. 10 )
enu.grep ( 3 .. 5 )
|
Output:
[3, 4, 5]
Example 2:
enu = ( 1 .. 10 )
enu.grep ( 3 .. 5 ) { |obj| obj % 2 == 1 }
|
Output:
[true, false, true]
Share your thoughts in the comments
Please Login to comment...