Looping
You can loop over a collection use for
, any
, or all
. any
/all
are identical in a loop context, just use all
if your loop body returns true or any
if the body returns false. A loop body with multiple lines will always return false. The only time for
is shorter is when body is a single line and the collection needs parentheses around it to loop over with all
/any
. Examples:
for(i in 1..10)System.print(i)
// Is shorter than
(1..10).all{|i|System.print(i)}
a.all{|i|System.print(i)}
// Is shorter than
for(i in a)System.print(i)
(1..10).any{|i|
i=i*3
System.print(i)
}
// Is shorter than
for(i in 1..10){
i=i*3
System.print(i)
}
In addition to using these for regular looping, any
and all
the return values of any
and all
can actually be put to use, as can related collection methods like where
, map
, and reduce
.
Avoid variable declarations
Creating variables using var
is expensive, its better to reuse variables when you can. Like in many other langs, if you are looping over a collection, you can reuse that collection's name as a variable inside the loop. Combine this with creating a short alias for Process
and you will have a free variable on most argument holes. ie:
import"os"for Process as a
a.arguments.any{|b|
a=2
System.print(b*a)
}
Remember that you can assign a value to a variable that doesn't match its current type, so a string variable that you no longer need can be repurposed to an int, and so on.
Also, there is a preinitialized variable that may be useful: Fn
. If you only need to use a variable's name 3 times in your code, using Fn
is shorter than declaring one with var
.
// Compare
Fn=1;Fn=2;Fn=3;
var a=1;a=2;a=3;
If you need a whole bunch of variables and can't get away with reuse, you may be able to save using function parameters:
Fn.new{|a,b,c,d,e,f,g,h,i,j|
a=b*c
System.print("%(a) %(b) %(c) %(d) %(e) %(f) %(g) %(h) %(i) %(j)")
}.call(1,2,3,4,5,6,7,8,9,10)
Short-Circuiting
Like many other languages, Wren supports conditional short-circuiting.
for(i in 1..100)if(i%7<1)System.print(i)
// is the same as
for(i in 1..100)i%7<1&&System.print(i)