...

/

Block Return Values

Block Return Values

This lesson discusses how and what a block returns.

Remember that we said a block returns a value just like methods do? So far, in our two examples above, we did not do anything with the return values of the block.

Example

Here’s an example that does that:

Press + to interact
p [1, 2, 3, 4, 5].collect { |number| number + 1 }

This will take the array of numbers, and transform it into another array.

Explanation

  • It does this by calling the method collect on the original array, which calls the given block for each of the elements and collects each of the return values returned by the block. The resulting array is then returned by the method collect, and printed to the screen.

  • In other words, the method collect uses the block as a transformer. It takes each element of the array, passes it to the block in order to transform it to something else, and then keeps all the transformed values in a ...

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy