Ruby | Enumerable flat_map function

The flat_map() of enumerable is an inbuilt method in Ruby returns a new array with the concatenated results of running block once for every element in enum. In case no block is given, an enumerator is returned instead.

Syntax: block.flat_map { |obj| block }

Parameters: The function takes the block according to which the every block is to be returned. If no block is given, an enumerator is returned.



Return Value: It returns a new array.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for flat_map method in Enumerable
  
# Initialize
enu = [12, 18]
  
# returns enumerator
res = enu.flat_map { |el| [2*el, 3*el] }

chevron_right


Output:

[24, 36, 36, 54]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for flat_map method in Enumerable
  
# Initialize
enu = [[17, 21], [19, 100]]
  
# returns enumerator
res = enu.flat_map { |el| el + [1000] }

chevron_right


Output:

[17, 21, 1000, 19, 100, 1000]


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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.