Blocks
In Sidef, a block of code is an object which encapsulates zero or more expressions and is delimited by a pair of curly braces ({}).
1
var block = {
2
say "Hello, World!"
3
}
Copied!

Block parameters

For declaring block parameters, Sidef borrows Ruby's way of doing this, by using the |arg1, arg2, ...| special syntax:
1
{ |a, b|
2
3
say a # prints: 1
4
say b # prints: 2
5
6
}(1, 2)
Copied!

Callbacks

Blocks are also used as arguments to many built-in methods as callback blocks:
1
{ print "Sidef! " } * 3 # prints "Sidef! Sidef! Sidef! "
2
5.times {|x| print x } # prints "01234"
3
[1,2,3].sort {|a,b| b <=> a } # returns a new array: [3,2,1]
Copied!
The Block class also implements some useful methods, such as:
1
say {|n| n**2 }.map(1..5) #=> [1, 4, 9, 16, 25]
2
say { .is_odd }.grep([1,2,3,4]) #=> [1, 3]
Copied!
Last modified 1yr ago
Copy link