Controlling the execution flow with conditionals
Crystal, like most imperative languages, has a top-to-bottom line-by-line flow of execution. After the current line is executed, the line below that will be the next one. But you are empowered to control and redirect this flow of execution based on any conditional expression you can think of. The first kind of flow control we will cover is precisely that, reacting to conditionals.
if and unless
An if
statement can be used to check a conditional; if it's truthy (that is, not nil
nor false
), then the statement inside it is executed. You can use else
to add an action in case the conditional isn't true
. See this, for example:
secret_number = rand(1..5) # A random integer between 1 and 5 print "Please input your guess: " guess = read_line.to_i if guess == secret_number puts "You guessed correctly!" else puts "Sorry, the number was #{secret_number}." end
The conditional...