Looping through a series – foreach and forall

In many cases, you'll want to go through an entire series, executing code for each item in the series, using something easier than next. Red has the foreach and forall words to do just that.

The foreach word executes a code block for each item in the series:

names: ["John" "Dave" "Jane"]foreach name names [print name]

This prints out the following:

John    DaveJane

You should choose a descriptive word for the iteration variable (here, we have used name). It takes on the values of the items one by one, in order.

The forall word also moves through the series, but it executes a code block for all the items together, and combines this with a next at each iteration:

forall names [print names]

This ...

Get Learn Red - Fundamentals of Red now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.