Ruby学习笔记(04)_判断

来源:互联网 发布:网络教育本科收费标准 编辑:程序博客网 时间:2024/06/02 00:13

if…else语句

语法:

if conditional [then]      code...[elsif conditional [then]      code...]...[else      code...]end

if 表达式用于条件执行。值 false 和 nil 为假,其他值都为真。请注意,Ruby 使用 elsif,不是使用 else if 和 elif。
如果 conditional 为真,则执行 code。如果 conditional 不为真,则执行 else 子句中指定的 code。
通常我们省略保留字 then 。若想在一行内写出完整的 if 式,则必须以 then 隔开条件式和程式区块。如下所示:

if a == 4 then a = 7 end

实例:

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

同时注意一般Ruby约定判断真假值的方法命名都以?结尾,例如

p "".empty? #=> false

Ruby if 修饰符

语法:

code if condition

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

#!/usr/bin/ruby$debug=1print "debug\n" if $debug#输出结果:debug

Ruby unless 语句

语法:

unless conditional [then]   code[else   code ]end

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

#!/usr/bin/ruby# -*- coding: UTF-8 -*-x=1unless x>2   puts "x 小于 2" else  puts "x 大于 2"end#输出结果:x 小于 2

Ruby unless 修饰符

语法:

code unless conditional

如果 conditional 为假,则执行 code。

Ruby case 语句

语法:

case expression[when expression [, expression ...] [then]   code ]...[else   code ]end

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

=== 与 case 语句
在 case 语句中,when 判断值是否相等时,实际是使用 === 运算符来判断的。左边是数值或者字符串时,=== 与== 的意义是一样的,除此以外,===
还可以与=~ 一样用来判断正则表达式是否匹配,或者判断右边的对象是否属于左边的类,等等。对比单纯的判断两边的值是否相等,=== 能表达更加广义的“相等”。

因此:

case expr0when expr1, expr2   stmt1when expr3, expr4   stmt2else   stmt3end

基本类似:

_tmp = expr0if expr1 === _tmp || expr2 === _tmp   stmt1elsif expr3 === _tmp || expr4 === _tmp   stmt2else   stmt3end

实例:

#!/usr/bin/ruby# -*- coding: UTF-8 -*-$age =  5case $agewhen 0 .. 2    puts "婴儿"when 3 .. 6    puts "小孩"when 7 .. 12    puts "child"when 13 .. 18    puts "少年"else    puts "其他年龄段的"end#结果输出:小孩

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

foo = falsebar = truequu = falsecasewhen foo then puts 'foo is true'when bar then puts 'bar is true'when quu then puts 'quu is true'end# 显示 "bar is true
原创粉丝点击