Control flow
if, elsif, else #
The condition must be a Bool.
def main() -> Void
temperature = 18
if temperature > 25
puts("hot")
elsif temperature > 15
puts("mild")
else
puts("cold")
end
endmildBoolean operators #
and, or and not (or &&, ||, !) combine Bool values. and and or stop early when the left side decides the answer.
def main() -> Void
sunny = true
warm = false
puts(sunny and warm)
puts(sunny || warm)
puts(not warm)
puts(!(sunny && warm))
endfalse
true
true
truewhile #
while repeats its block while the condition holds.
def main() -> Void
n = 1
while n < 50
n *= 3
end
puts(n)
end81for #
for walks through a list. The loop variable is read-only. Use _ to drop it (see Variables).
def main() -> Void
for fruit in ["apple", "pear", "plum"]
puts(fruit)
end
for _ in 1..2 # the body does not need the number
puts("tick")
end
endapple
pear
plum
tick
tickTo count, walk through a range: a..b includes b, a...b leaves it out. n.times runs a block n times. See Range for more.
def main() -> Void
for i in 1..3
puts(i)
end
2.times do |i| puts("round #{i}") end
end1
2
3
round 0
round 1break and next #
break leaves the loop. next skips to the next round. When one of them, or a return, depends on a condition, write the condition after it: next if c is the if c with next and end written out. Only return, break and next take this guard, and it has one condition: there is no unless, and no else.
def main() -> Void
for n in [1, 2, 3, 4, 5, 6]
next if n % 2 == 0
break if n > 4
puts(n)
end
end1
3A statement after return, break or next, or after an if or case whose every branch ends in one, can never run, so it is an error (CHECK-UNREACHABLE-CODE). Remove it or move it before.
def main() -> Void
for n in [1, 2, 3]
if n == 2
break
puts("never")
end
puts(n)
end
enderror[CHECK-UNREACHABLE-CODE]case on values #
case runs the first arm that matches; _ matches anything. On a number, string or Bool, end with a _ arm.
def describe(n: Int) -> String
case n
0 -> "zero"
1 -> "one"
_ -> "many"
end
end
def main() -> Void
puts(describe(0))
puts(describe(1))
puts(describe(7))
endzero
one
manyAn arm can hold more lines:
def main() -> Void
command = "add"
total = 10
case command
"add" ->
total += 5
puts("added")
"reset" -> total = 0
_ -> puts("unknown command")
end
puts(total)
endadded
15case is most useful with enums: see Enums and case.
Statements, not expressions #
if and case give no value. Assign inside them, or return from them:
def sign(n: Int) -> String
word = "not negative"
if n < 0
word = "negative"
end
word
end
def main() -> Void
puts(sign(-3))
endnegative