elsifStatements in Ruby
In Ruby, an
elsif statement can be placed between
else statements. It allows us to check for additional conditions.
More than one
elsif can be placed between
print "enter a number: "num = gets.chompnum = num.to_i;if num == 5print "number is 5"elsif num == 10print "number is 10"elsif num == 11print "number is 11"elseprint "number is something other than 5, 10, or 11"end
! (not) operator in Ruby flips a boolean value. If a value is
true then applying
! to the value changes it to
false and vice versa.
data = true;puts !data;# Output: false
In Ruby, an
if statement evaluates to either
false. The code indented after the
if portion is executed for
true while the code indented after the
else portion is executed for
if number > 50print "number is greater than 50"elseprint "number is not greater than 50"end
The following comparison or relational operators are used in Ruby to compare values.
> - greater than;
< - less than;
>= - greater than or equal to;
<= - less than or equal to;
== - equal to
a = 1;b = 2;c = 2;puts a > b;puts a < b;puts b >= c;puts a <= c;puts b == c;# Output:# false# true# true# true# true
|| (or) operator is a logical operator which returns
true if either of the expressions on left-hand side or right-hand side is
grade1 = 50grade2 = 30grade3 = 80if grade1 > grade2 || grade1 > grade3puts "Grade 1 is not the lowest score!"end
ifStatement in Ruby
if statement in Ruby evaluates an expression, which returns either
false. If the expression is
true, Ruby executes the code block that follows the
if whereas if the expression is
false, Ruby returns nil.
In this example, the string
"Your condition was true!" will print because the condition
number == 10 is true.
number = 10if number == 10puts "Your condition was true!"end
&& is a logical operator in Ruby which evaluates to
true only if both expressions on either side of
&& evaluates to
if score1 > score2 && score1 > score3print "Score 1 is the greatest in value."elseprint "Score 1 is not the greatest in value."end
unless statement in Ruby is used to evaluate an expression. If the expression evaluates to
false, then the code following
unless is executed.
#This construct requires a "number" variable to be less than 10 in order to execute:print "Enter a number"number = gets.to_iunless number >= 10puts "number is less than 10."end