The array.collect
or the collect
method is used to call the block argument given to it on each element of an array. The block returns a new array after this operation.
array.collect{|item|block}
item
: Represents an item in the array.
block
: Contains instructions on what happens to each element.
A new array that contains values returned by the block.
In the example below, we’ll create an array of numbers and use collect
to add 2 to each element. This increases each element of the array by 2 in the returned value.
# create an arrayarray = [1, 2, 3, 4, 5]# use the collect to# add 2 to each element in# the arraynewArray = array.collect{|item| item + 2}# print the returne value to# the console.puts "#{newArray}"
When we click the “Run” button, elements in the original array are incremented by 2 in the new array. This is a typical use of the collect()
method.