Functions and Blocks

Collect in Ruby

Applies a block onto every item in an array.


Syntax
array.collect { |element| #code to run on element }

Notes

Collect does not modify an array, rather it returns a copy.


Example
numberLine = [ 1, 2, 3, 4, 5 ]
shiftedNumberLine = numberLine.collect { |number| number + 1 }

#shiftedNumberLine is [2, 3, 4, 5, 6]

Add to Slack

< Blocks   |   Yield >

© 2018 SyntaxDB. All Rights Reserved.