当前位置:  首页>> 技术小册>> Ruby入门教程

Ruby 提供了几种很常见的条件结构。在这里,我们将解释所有的条件语句和 Ruby 中可用的修饰符。

  1. Ruby if...else 语句

语法

  1. if conditional [then]
  2. code...
  3. [elsif conditional [then]
  4. code...]...
  5. [else
  6. code...]
  7. end

if 表达式用于条件执行。值 false 和 nil 为假,其他值都为真。请注意,Ruby 使用 elsif,不是使用 else if 和 elif。

如果 conditional 为真,则执行 code。如果 conditional 不为真,则执行 else 子句中指定的 code。

通常我们省略保留字 then 。若想在一行内写出完整的 if 式,则必须以 then 隔开条件式和程式区块。如下所示:

  1. if a == 4 then a = 7 end

实例

  1. #!/usr/bin/ruby
  2. # -*- coding: UTF-8 -*-
  3. x=1
  4. if x > 2
  5. puts "x 大于 2"
  6. elsif x <= 2 and x!=0
  7. puts "x 是 1"
  8. else
  9. puts "无法得知 x 的值"
  10. end

以上实例输出结果:

  1. x 1

Ruby if 修饰符

语法

  1. code if condition

if修饰词组表示当 if 右边之条件成立时才执行 if 左边的式子。即如果 conditional 为真,则执行 code。

实例

  1. #!/usr/bin/ruby
  2. $debug=1
  3. print "debug\n" if $debug

以上实例输出结果:

  1. debug

Ruby unless 语句

语法

  1. unless conditional [then]
  2. code
  3. [else
  4. code ]
  5. end

unless式和 if式作用相反,即如果 conditional 为假,则执行 code。如果 conditional 为真,则执行 else 子句中指定的 code。

实例

  1. #!/usr/bin/ruby
  2. # -*- coding: UTF-8 -*-
  3. x=1
  4. unless x>2
  5. puts "x 小于或等于 2"
  6. else
  7. puts "x 大于 2"
  8. end

以上实例输出结果为:

  1. x 小于或等于 2

Ruby unless 修饰符

语法

  1. code unless conditional

如果 conditional 为假,则执行 code。

实例

  1. #!/usr/bin/ruby
  2. # -*- coding: UTF-8 -*-
  3. $var = 1
  4. print "1 -- 这一行输出\n" if $var
  5. print "2 -- 这一行不输出\n" unless $var
  6. $var = false
  7. print "3 -- 这一行输出\n" unless $var

以上实例输出结果:

  1. 1 -- 这一行输出
  2. 3 -- 这一行输出

Ruby case 语句

语法

  1. case expression
  2. [when expression [, expression ...] [then]
  3. code ]...
  4. [else
  5. code ]
  6. end

case先对一个 expression 进行匹配判断,然后根据匹配结果进行分支选择。

它使用 ===运算符比较 when 指定的 expression,若一致的话就执行 when 部分的内容。

通常我们省略保留字 then 。若想在一行内写出完整的 when 式,则必须以 then 隔开条件式和程式区块。如下所示:

  1. when a == 4 then a = 7 end

因此:

  1. case expr0
  2. when expr1, expr2
  3. stmt1
  4. when expr3, expr4
  5. stmt2
  6. else
  7. stmt3
  8. end

基本上类似于:

  1. _tmp = expr0
  2. if expr1 === _tmp || expr2 === _tmp
  3. stmt1
  4. elsif expr3 === _tmp || expr4 === _tmp
  5. stmt2
  6. else
  7. stmt3
  8. end

实例

  1. #!/usr/bin/ruby
  2. # -*- coding: UTF-8 -*-
  3. $age = 5
  4. case $age
  5. when 0 .. 2
  6. puts "婴儿"
  7. when 3 .. 6
  8. puts "小孩"
  9. when 7 .. 12
  10. puts "child"
  11. when 13 .. 18
  12. puts "少年"
  13. else
  14. puts "其他年龄段的"
  15. end

以上实例输出结果为:

  1. 小孩

当case的”表达式”部分被省略时,将计算第一个when条件部分为真的表达式。

  1. foo = false
  2. bar = true
  3. quu = false
  4. case
  5. when foo then puts 'foo is true'
  6. when bar then puts 'bar is true'
  7. when quu then puts 'quu is true'
  8. end
  9. # 显示 "bar is true"

该分类下的相关小册推荐:

暂无相关推荐.