|
You will use control structure when running a certain instruction or more is dependent on the the truth value of a conditions.So, for example, you want to print something on the screen if x=3, and print something different if x is not equal to 3.
To do this, you would need to use a control structure called the if...else structure.
The syntax for the if...else control structure is this:
if condition
instruction1
instruction2
............
instructionm
else
instructionm+1
instructionm+2
..............
instructionl
end
Notice that you can have as many instructions to be executed as you want.Unlike other programming languages(in case you are familiar with others), Ruby does not require the instructions to be put inside curly braces {} as you would have to do it C++ for example.
Instead, the keyword "end" is used to mark the end of the if...else control structure.
Now let me explain what all of the above does:
The program evaluates the "condition".If the condition is true, then the program execute all the instructions from instruction1 all the way to instructionm
If the condition is false, the program jumps to the "else" branch of code and executes all the statements from instructionm+1 to instructionl.
The if...elsif...else control structure does a similar thing, except you'd be using this when you need to test more things and have more conditional behaviours.
The general syntax is:
if condition1
instruction1
............
instructionm
elsif condition2
instructionm+1
..............
instructionk
else
instructionk+1
instructionl
end
This control structure does this: the program evaluates the "condition1".If condition1 is true then instruction1 to instructiom are executed.
If condition1 is false, then the program will evaluate condition2.If condition2 is true, the program will execute instructionm+1 to instructionk.
If condition2 is also false, the program will execute instructionk+1 to instructionl.
Now here's a situation where you can use a control structure.
x==1
if x>2
puts "x is greater than 2"
elsif x<=2 and x!=0
puts "x is 1"
else
puts "i can't guess the number"
end
This would work only if the number was an integer, otherwise it would be a rather not very smart piece of code,but at least it servers the purpose of demonstrating you how the if...elsif...else conditional acts.
|