iyi

Playground · Data · 21 of 33

blocks

Blocks and closures: code you hand to a function.

samples/tour/blocks.iyi · blocks.wasm · 124 KB
# Blocks and closures: code you hand to a function.

# `yield` runs the block the caller passed.
def repeat(times : Int32)
  times.times { |i| yield i }
end

repeat(3) { |i| puts "step #{i}" }

# A block sees the variables around it.
total = 0
[1, 2, 3].each { |n| total += n }
puts total

# `->` makes a function value you can store and call later.
square = ->(x : Int32) { x * x }
puts square.call(7)

# It captures its surroundings too: this one counts every call.
count = 0
tick = ->() { count += 1 }
tick.call
tick.call
puts count

# A block parameter with a type, handed on as a value.
def apply(x : Int32, &f : Int32 -> Int32) : Int32
  f.call(x)
end

puts apply(5) { |v| v + 100 }
output
Press Run.

recorded with iyi 0.18.0 (built on Crystal 1.22.0-dev [2a9653052] (2026-10-18)) · Linux 7.0.0-38-generic x86_64, QEMU Virtual CPU version 2.5+ · 2026-10-19

You can type in the pane: nothing here compiles, so what you type cannot run, and the page says which bytes it is running the moment the text stops being the recorded file. There is no standard input, no filesystem and no threads on this target, and one sample fails on purpose for exactly that reason.

Run executes blocks.wasm, the module the compiler built from this file, in your browser. How this works

Try it on your machine

Copy the program into blocks.iyi, change something, and run it. Only a compiler on your own machine can run what you wrote.

sh, after installing
$ iyi run blocks.iyi