Ruby offers a conditional structure, which is common in modern programming languages. Here, we'll explain all of Ruby's conditional statements and modifiers
Ruby If...else Statement:
Syntax:
If conditional [then]
code ...
[elsif conditional [then]
code ...] ...
[Else
code ...]
End
An if expression is used for conditional execution. The value false and nil are false, and the rest are true. Note that Ruby strings use elsif, not else if and not elif.
The IF condition is ture executes the code. If the condition is not ture, the code specified in the ELSE clause is executed.
If the condition of an if expression is a reserved word, then a newline character or semicolon separates the code.
Instance:
#!/usr/bin/ruby
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
x is 1
Ruby If rhetorical character:
Syntax:
Code if condition
If condition is true execution code.
Instance:
#!/usr/bin/ruby
$debug =1
print "debug\n" if $debug
This will produce the following results:
Ruby unless statement:
Grammar:
Unless conditional [then]
code
[else
code]
end
Executes the code if the condition is false. If the condition is that the code specified in the FALSE,ELSE clause is executed.
For example:
#!/usr/bin/ruby
x=1
unless x>2
puts "x is less than 2"
else
puts "x is greater than 2"
End
This will produce the following results:
Ruby unless rhetoric characters:
Syntax:
Code unless conditional
Executes the code, False if there is a condition.
Instance:
#!/usr/bin/ruby
$var = 1
print "1--the value is set\n" if $var
print "2--the value is set\n" unless $var
$ var = false
print "3--Value is set\n" unless $var
This will produce the following results:
1--The value is set
3--the value is set
Ruby Case Statement
Syntax:
Case expression
[expression [, expression ...] [Then]
Code] ...
[Else
code]
end
The code executed when the = = = operator is used to match the specified terms, as specified by the comparison expression.
clause to calculate the expression specified by the When and the left operand. If no clause matches, the code else clause executes.
When the expression of the statement is reserved, then a newline character or semicolon separates the code.
So:
Case Expr0 when
expr1, expr2
stmt1 when
expr3, EXPR4
stmt2
Else
stmt3
End
is basically similar to the following:
_tmp = Expr0
if expr1 = = _tmp | | expr2 = = _tmp stmt1
elsif expr3 = = _tmp | | expr4 = = _TMP Stmt2
else
stmt3
End
Instance:
#!/usr/bin/ruby
$age = 5 case
$age when
0 ... 2
puts "Baby" when
3 ... 6
puts "little child"
whe N 7.
puts
puts "
youth"
else
puts "adult"
end
This will produce the following results: