Iterators and Blocks

Ruby like many other languages makes use of Higer Order Functions. To use them the first argument is a block. A block can be between do and end keywords

do
    puts "Hello"
end

or can be between braces { and }

{ puts "Hello" }

The Array Object has lots of methods that accept a block as an argument.

[1, 2, 3].map do |value|
    value * 2
end # => [2, 4, 6]

or with braces


[1, 2, 3].map { |value|
    value * 2
} # =>  [2, 4, 6]

and even shorter hand if it can fit.

[1, 2, 3].map { |value| value * 2 } # => [2, 4, 6]

TL;DR

Book

Pragmatic Ruby - containers, iterators and blocks

Exercises

Ruby Monk - control structures

Videos

Ruby Fundamentals - Iterators and blocks

Challenge 🎠

Use Rspec to run the challenges

bin/rspec spec/challenges/iterators-blocks_spec.rb --format doc

fix ../lib/challenges/iterators-blocks.rb so the tests pass ✔️

Go to next section

Exceptions