home/ atoms/ sonic-pi-times-iteration

N.times do ... end repeats a code block exactly N times then continues execution

N.times do … end is a compact loop construct that runs the block exactly N times then moves on, unlike loop which never terminates. It is idiomatic for counting patterns (e.g., 4.times for a 4-bar phrase) and can be nested to generate grid or polyrhythmic structures. Because it terminates, code after the block executes normally. N can be a variable.

Examples

4.times do sample :bd_haus sleep 0.5 end sample :drum_cymbal_open # plays after the 4 kicks

Assessment

Use 3.times and 2.times (nested) to produce a kick-snare-snare pattern repeating 3 times, then add a cymbal after all iterations.

“use this to create lots of nice repeating structures”
corpus · sonic-pi-built-in-tutorial · chunk 11