May 12, 2021 Ruby
Ruby provides conditional structures that are common in other modern languages. Here, we'll explain all the conditional statements and modifiers available in Ruby.
if conditional [then] code... [elsif conditional [then] code...]... [else code...] end
if a == 4 then a = 7 end
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
x=1
if x > 2
puts "x 大于 2"
elsif x <= 2 and x!=0
puts "x 是 1"
else
puts "无法得知 x 的值"
end
x 是 1
code if condition
If the conditional is true, code is executed.
#!/usr/bin/ruby $debug=1 print "debug\n" if $debugTry it out . . .
This results in the following:
debug
unless conditional [then] code [else code ] end
The unless and if operations are the opposite, i.e.
code
is executed if the
conditional is
false.
I
f
the conditional
is
true, the code specified in the else clause is
executed.
#!/usr/bin/ruby x=1 unless x>2 puts "x 小于 2" else puts "x 大于 2" endTry it out . . .
This results in the following:
x 小于 2
code unless conditional
If the conditional is false, code is executed.
#!/usr/bin/ruby # -*- coding: UTF-8 -*- $var = 1 print "1 -- 这一行输出\n" if $var print "2 -- 这一行不输出\n" unless $var $var = false print "3 -- 这一行输出\n" unless $var
This results in the following:
1 -- 这一行输出 3 -- 这一行输出
case expression [when expression [, expression ...] [then] code ]... [else code ] end
Case first matches an expression, and then branch selection based on the match results.
It === expression specified by when using the operator and executes the contents of the when section if consistent.
Usually we omit the reserved word then. I f you want to write the complete when formula in one line, you must separate the conditional and program chunks with then. Here's what it looks like:
when a == 4 then a = 7 end
So:
case expr0 when expr1, expr2 stmt1 when expr3, expr4 stmt2 else stmt3 end
Basically similar to:
_tmp = expr0 if expr1 === _tmp || expr2 === _tmp stmt1 elsif expr3 === _tmp || expr4 === _tmp stmt2 else stmt3 end
#!/usr/bin/ruby # -*- coding: UTF-8 -*- $age = 5 case $age when 0 .. 2 puts "婴儿" when 3 .. 6 puts "小孩" when 7 .. 12 puts "child" when 13 .. 18 puts "少年" else puts "其他年龄段的" end
This results in the following:
小孩