良许Linux教程网 干货合集 详解Ruby 判断语句

详解Ruby 判断语句

Ruby是一种解释型、面向对象、动态类型的语言。Ruby采取的策略是在灵活性和运行时安全之间寻找平衡点。随着Rails框架的出现,Ruby也在2006年前后一鸣惊人,同时也指引人们重新找回编程乐趣,下面为大家详细讲解一下Ruby 判断语句。

img

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

Ruby 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=1
if x > 2
  puts "x 大于 2"
elsif x "x 是 1"
else
  puts "无法得知 x 的值"
end

以上实例输出结果:

x 是 1

Ruby if 修饰符

语法

code if condition

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

实例

#!/usr/bin/ruby

$debug=1
print "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。

实例

#!/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 语句

语法

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

case先对一个 expression 进行匹配判断,然后根据匹配结果进行分支选择。 它使用 ===运算符比较 when 指定的 expression,若一致的话就执行 when 部分的内容。 通常我们省略保留字 then 。若想在一行内写出完整的 when 式,则必须以 then 隔开条件式和程式区块。如下所示:

when a == 4 then a = 7 end

因此:

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 =  5
case $age
when 0 .. 2
   puts "婴儿"
when 3 .. 6
   puts "小孩"
when 7 .. 12
   puts "child"
when 13 .. 18
   puts "少年"
else
   puts "其他年龄段的"
end

以上实例输出结果为:

小孩

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

foo = false
bar = true
quu = false

case
when foo then puts 'foo is true'
when bar then puts 'bar is true'
when quu then puts 'quu is true'
end
# 显示 "bar is true"

以上就是良许教程网为各位朋友分享的Linux系统相关内容。想要了解更多Linux相关知识记得关注公众号“良许Linux”,或扫描下方二维码进行关注,更多干货等着你 !

img
本文由 良许Linux教程网 发布,可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。
良许

作者: 良许

良许,世界500强企业Linux开发工程师,公众号【良许Linux】的作者,全网拥有超30W粉丝。个人标签:创业者,CSDN学院讲师,副业达人,流量玩家,摄影爱好者。
上一篇
下一篇

发表评论

联系我们

联系我们

公众号:良许Linux

在线咨询: QQ交谈

邮箱: yychuyu@163.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部