What is array.collect in Ruby?

Overview

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.

Syntax

array.collect{|item|block}

Parameter

item: Represents an item in the array.

block: Contains instructions on what happens to each element.

Return value

A new array that contains values returned by the block.

Example

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 array
array = [1, 2, 3, 4, 5]
# use the collect to
# add 2 to each element in
# the array
newArray = 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.

Free Resources