Ruby提供了对现代语言非常常见的条件结构.在这里,我们将解释Ruby中可用的所有条件语句和修饰符.
if conditional [then] code... [elsif conditional [then] code...]... [else code...] end
如果使用表达式用于条件执行.值 false 和 nil 为false,其他一切都为真.注意Ruby使用elsif,否则if if elif.
如果条件为真,则执行代码.如果条件不为真,则执行else子句中指定的代码.
if表达式的条件通过保留字然后,换行符或分号与代码分开.
#!/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
code if condition
如果条件为真,则执行代码.
#!/usr/bin/ruby $debug = 1 print "debug\n" if $debug
这将产生以下结果 :
debug
unless conditional [then] code [else code ] end
如果条件为假,则执行代码.如果条件为真,则执行else子句中指定的代码.
#!/usr/bin/ruby x = 1 unless x>=2 puts "x is less than 2" else puts "x is greater than 2" end
这将产生以下结果 :
x is less than 2
code unless conditional
执行代码如果条件为假.
#!/usr/bin/ruby $var = 1 print "1 -- Value is set\n" if $var print "2 -- Value is set\n" unless $var $var = false print "3 -- Value is set\n" unless $var
这将产生以下结果 :
1 -- Value is set 3 -- Value is set
case expression [when expression [, expression ...] [then] code ]... [else code ] end
比较case指定的表达式和使用===运算符时指定的表达式并执行匹配的when子句的代码.
由when子句指定的表达式被计算为左操作数.如果no子句匹配时, case 执行 else 子句的代码.
A 当语句时表达式通过保留字,换行符或分号与代码分隔开.因此 :
case expr0 when expr1, expr2 stmt1 when expr3, expr4 stmt2 else stmt3 end
基本类似于以下 :
_tmp = expr0 if expr1 === _tmp || expr2 === _tmp stmt1 elsif expr3 === _tmp || expr4 === _tmp stmt2 else stmt3 end
#!/usr/bin/ruby $age = 5 case $age when 0 .. 2 puts "baby" when 3 .. 6 puts "little child" when 7 .. 12 puts "child" when 13 .. 18 puts "youth" else puts "adult" end
这将产生以下结果 :
little child