Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
ruby
communitycreator

What is array.collect in Ruby?

okwudili onyejiaku

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.

RELATED TAGS

array
ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring