Related Articles

Related Articles

Ruby | Enumerable collect() function
  • Last Updated : 05 Dec, 2019

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:



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[20, 30, 40, 50, 60]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[nil, nil, nil, nil, nil]
My Personal Notes arrow_drop_up
Recommended Articles
Page :