Block Return Values
Learn about block return values.
Remember when we learned that a block returns a value just like methods do? So far, in our two previous examples, we didn’t do anything with the block’s return values.
An example using collect
Here’s an example that does that:
Press + to interact
Ruby
p [1, 2, 3, 4, 5].collect { |number| number + 1 }
This takes the array of numbers and transforms it into another array.
Explanation
-
It does this by calling the
collect
method on the original array, which executes the given block for each element and collects each array return value returned by the block. The resulting array is then returned by thecollect
method and printed to the screen. -
In other words, the
collect
method uses the block as a transformer. It takes each element of the array, passes it to the ...