Explain in detail the condition judgment statements in Ruby and explain the ruby judgment statements
Ruby provides conditional structures, which are common in modern programming languages. Here, we will explain all the Ruby conditional statements and modifiers.
Ruby if... else statement:
Syntax:
if conditional [then] code...[elsif conditional [then] code...]...[else code...]end
If expression is used for conditional execution. Values false and nil are both false, and others are true. Note that the Ruby string uses elsif, neither else if nor elif.
If the condition is true, the code is executed. If the condition is not true, the Code specified in the else clause is executed.
If expressions are reserved words, a linefeed or semicolon is used to separate the code.
Instance:
#!/usr/bin/rubyx=1if 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"endx is 1
Ruby if rhetoric:
Syntax:
Code if condition
The if condition is true.
Instance:
#!/usr/bin/ruby$debug=1print "debug\n" if $debug
This produces the following results:
debug
Ruby unless statement:
Syntax:
unless conditional [then] code[else code ]end
If the condition is false, run the code. If the condition is false, the Code specified in the else clause is executed.
For example:
#!/usr/bin/rubyx=1unless x>2 puts "x is less than 2" else puts "x is greater than 2"end
This produces the following results:
x is less than 2
Ruby unless rhetoric:
Syntax:
Code unless conditional
Run the Code. If conditions exist, the code is false.
Instance:
#!/usr/bin/ruby$var = 1print "1 -- Value is set\n" if $varprint "2 -- Value is set\n" unless $var$var = falseprint "3 -- Value is set\n" unless $var
This produces the following results:
1 -- Value is set3 -- Value is set
Ruby case statement
Syntax:
case expression[when expression [, expression ...] [then] code ]...[else code ]end
When a comparison expression is specified, the Code executed when the = Operator is used to match the specified terms.
Clause calculates the expressions specified by the when and left operands. If no clause matches, the Code else clause is executed.
If the expression of the when statement is reserved, A linefeed or semicolon is used to separate the code.
So:
case expr0when expr1, expr2 stmt1when expr3, expr4 stmt2else stmt3end
It is basically similar to the following:
_tmp = expr0if expr1 === _tmp || expr2 === _tmp stmt1elsif expr3 === _tmp || expr4 === _tmp stmt2else stmt3end
Instance:
#!/usr/bin/ruby$age = 5case $agewhen 0 .. 2 puts "baby"when 3 .. 6 puts "little child"when 7 .. 12 puts "child"when 13 .. 18 puts "youth"else puts "adult"end
This produces the following results:
little child