Open In App

Ruby | Enumerable collect() function

Improve
Improve
Like Article
Like
Save
Share
Report

The collect() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum. The object is repeated every time for each enum. In case no object is given, it return nil for each enum.

Syntax: (r1..r2).collect { |obj| block }

Parameters: The function takes the object and the block which is for every enum, it also takes r1 and r2 which decides on the number of elements in the returned enumerable.

Return Value: It returns a new array.

Example 1:




# Ruby program for collect? method in Enumerable
  
# returns enumerator
enu1 = (2..6).collect {|x| x * 10}


Output:

[20, 30, 40, 50, 60]

Example 2:




# Ruby program for collect? method in Enumerable
  
  
# returns an enumerator with nil
enu1 = (2..6).collect {}


Output:

[nil, nil, nil, nil, nil]

Last Updated : 05 Dec, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads