Ruby判断语句有哪些
本文小编为大家详细介绍“Ruby判断语句有哪些”,内容详细,步骤清晰,细节处理妥当,希望这篇“Ruby判断语句有哪些”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
语法
ifconditional[then]code...[elsifconditional[then]code...]...[elsecode...]end
if 表达式用于条件执行。值 false 和 nil 为假,其他值都为真。请注意,Ruby 使用 elsif,不是使用 else if 和 elif。 如果 conditional 为真,则执行 code。如果 conditional 不为真,则执行 else 子句中指定的 code。 通常我们省略保留字 then 。若想在一行内写出完整的 if 式,则必须以 then 隔开条件式和程式区块。如下所示:
ifa==4thena=7end
实例
#!/usr/bin/ruby#-*-coding:UTF-8-*-x=1ifx>2puts"x大于2"elsifx"x是1"elseputs"无法得知x的值"end
以上实例输出结果:
x是1Ruby if 修饰符
语法
codeifcondition
if修饰词组表示当 if 右边之条件成立时才执行 if 左边的式子。即如果 conditional 为真,则执行 code。
实例
#!/usr/bin/ruby$debug=1print"debug\n"if$debug
以上实例输出结果:
debugRuby unless 语句
语法
unlessconditional[then]code[elsecode]end
unless式和 if式作用相反,即如果 conditional 为假,则执行 code。如果 conditional 为真,则执行 else 子句中指定的 code。
实例
#!/usr/bin/ruby#-*-coding:UTF-8-*-x=1unlessx>2puts"x小于2"elseputs"x大于2"end
以上实例输出结果为:
x小于2Ruby unless 修饰符
语法
codeunlessconditional
如果 conditional 为假,则执行 code。
实例
#!/usr/bin/ruby#-*-coding:UTF-8-*-$var=1print"1--这一行输出\n"if$varprint"2--这一行不输出\n"unless$var$var=falseprint"3--这一行输出\n"unless$var
以上实例输出结果:
1--这一行输出3--这一行输出Ruby case 语句
语法
caseexpression[whenexpression[,expression...][then]code]...[elsecode]end
case先对一个 expression 进行匹配判断,然后根据匹配结果进行分支选择。 它使用 ===运算符比较 when 指定的 expression,若一致的话就执行 when 部分的内容。 通常我们省略保留字 then 。若想在一行内写出完整的 when 式,则必须以 then 隔开条件式和程式区块。如下所示:
whena==4thena=7end
因此:
caseexpr0whenexpr1,expr2stmt1whenexpr3,expr4stmt2elsestmt3end
基本上类似于:
_tmp=expr0ifexpr1===_tmp||expr2===_tmpstmt1elsifexpr3===_tmp||expr4===_tmpstmt2elsestmt3end
实例
#!/usr/bin/ruby#-*-coding:UTF-8-*-$age=5case$agewhen0..2puts"婴儿"when3..6puts"小孩"when7..12puts"child"when13..18puts"少年"elseputs"其他年龄段的"end
以上实例输出结果为:
小孩
当case的”表达式”部分被省略时,将计算第一个when条件部分为真的表达式。
foo=falsebar=truequu=falsecasewhenfoothenputs'fooistrue'whenbarthenputs'baristrue'whenquuthenputs'quuistrue'end#显示"baristrue"
读到这里,这篇“Ruby判断语句有哪些”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。