Decision Making in Ruby
Decision making statements are used to run one set of statements or another set of statements based on some conditions.
Ruby: if
statement
Let's use ruby scripts. Type notepad filename.rb
. This prompts to create a new file, type yes. You can also other text editors as per you liking.
#if comparison (relational expression)
# statements
#end
grade = gets
grade = Integer(grade)
if grade >= 70
puts "pass"
end
This is the code snippet of the program. Any statements that begins with # sign
are comments. They are non-executable statements and are used for better understanding of a program.
Syntax of If
statement:
if (condition)
statements
end
If the condition is true, then the statements inside if
block are executed.
When running the program, it prompts the user to enter grade and it is converted to Integer
. If grade entered is greater than 70 then it displays pass
.
You can see, when the value greater than 70 is entered, it displayed pass. If a value less than 70 is entered it displays nothing. To handle this, we need another type of statement called If - else
.
Ruby: if...else
statement
If else statements execute one set of statements if the condition is true or another set of statements if the condition is false.
Syntax of If- else statement:
if (condition)
statements1
else
statements2
end
If the condition is true the statements inside if block is executed, if condition fails the statements inside else block are executed.
If value less than 70 is entered it displays fail
.
If else statements are used for two way decisions. If we want to have more than two decisions, we can use If - Else If
statement.
If - Else If Statement:
It is used to make more complex branching statements.
Syntax of If - Else If statement is
if (condition1)
statements1
elsif (condition2)
statements2
elsif (condition n)
statements3
else
statements4
end
It evaluates the condition1, if it is true it executes statements1, if the condition is false it evaluates the condtion2, if true it executes statements2 and so on. If none of the conditions is true, it executes statements4.
Executing this program, prompts to enter the marks. Based on the value entered it checks the condition given in the program and displays your Grade
.
Ruby: Case statements
An alternate to the If - else if statement is Case statement
. It is also used for making multiple decisions. We can make multiple decisions in a structured way using Case statement.
Syntax of Case statement:
case (expression)
when expression1
statements1
when expression2
statements2
else
statements3
end
If the value of the variable grade is between 90 and 100 it assigns A
to the variable letterGrade
. Likewise, based on the input when the corresponding expression is met the following statements are executed.