Please expand this article or section. You can help by adding more information if you are an editor. More information might be found in a section of the talk page. (August 2018) |
Most programming languages have some sort of if-else statement.[citation needed]
If and If-Else Statements
In Scratch, an if-else statement is shown like so:
if <> then else
In Ruby, one can write an if-else statement like this:
if
# Code
else
# Code
end
In both languages, one can insert something that returns either true
or false
after "if", and some code in the if-else statement, like so:
if <[1] = [2]> then set [variable v] to [5] else set [variable v] to [6] end
if 1 == 2
variable = 5
else
variable = 6
end
Also in both languages, one can shorten it to just an if statement if an else is not needed for that particular situation.
if <[1] = [2]> then set [variable v] to [5] end
if 1 == 2
variable = 5
end
If-Elsif-Else Statements
In Ruby, there's an extra statement like this, called the "if-elsif-else" statement. It is shown like this:
if
# Code
elsif
# Code
else
# Code
end
In the code above, if the condition after "if" is true, it will execute that code. If it's not, it will move onto the elsif. After "elsif", there is a condition. If that's true, it will do that code. If it's not, it will do the code in the else statement.
The equivelent for these statements in Scratch would be:
if <> then else if <> then else end
One can add more elsifs as needed, which would turn the statement into an if-elsif-elsif-etc.-else statement.
if 5 == 5
# Code
elsif 4 == 2
# Code
elsif 8 == 9
# Code
elsif x > 3
# Code
else
# Code
end
Case Statements
There's another statement called the case statement. It is written in Ruby like this:
case
when
# Code
when
# Code
when
# Code
else
# Code
end
Here's a case statement with code and stuff in it:
case var
when 5
var += 1
when 3
puts "Hello, World!"
when 2
print "No enter after me... :("
else
puts "If neither 5, 3, nor 2 is equal to var, I will be executed!"
var = 1000000
end