Ruby 教程
- 第1节:Ruby 简介
- 第2节:Ruby 环境
- 第3节:Ruby 安装 – Unix
- 第4节:Ruby 安装 – Windows
- 第5节:Ruby 中文编码
- 第6节:Ruby 命令行选项
- 第7节:Ruby 环境变量
- 第8节:Ruby 语法
- 第9节:Ruby 数据类型
- 第10节:Ruby 类和对象
- 第11节:Ruby 类案例
- 第12节:Ruby 变量
- 第13节:Ruby 运算符
- 第14节:Ruby 注释
- 第15节:Ruby 条件判断
- 第16节:Ruby 循环
- 第17节:Ruby 方法
- 第18节:Ruby 块
- 第19节:Ruby 模块(Module)
- 第20节:Ruby 字符串(String)
- 第21节:Ruby 数组(Array)
- 第22节:Ruby 哈希(Hash)
- 第23节:Ruby 日期 & 时间(Date & Time)
- 第24节:Ruby 范围(Range)
- 第25节:Ruby 迭代器
- 第26节:Ruby 文件的输入与输出
- 第27节:Ruby File 类和方法
- 第28节:Ruby Dir 类和方法
- 第29节:Ruby 异常
- 第30节:Ruby 面向对象
- 第31节:Ruby 正则表达式
- 第32节:Ruby 数据库访问 – DBI 教程
- 第33节:Ruby 连接 Mysql – MySql2
- 第34节:Ruby CGI 编程
- 第35节:Ruby CGI方法
- 第36节:Ruby CGI Cookies
- 第37节:Ruby CGI Sessions
- 第38节:Ruby 发送邮件 – SMTP
- 第39节:Ruby Socket 编程
- 第40节:Ruby XML, XSLT 和 XPath 教程
- 第41节:Ruby Web Services 应用 – SOAP4R
- 第42节:Ruby 多线程
- 第43节:Ruby JSON
- 第44节:Ruby RubyGems
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 <= 2 and x!=0
puts "x 是 1"
else
puts "无法得知 x 的值"
end
以上实例输出结果:
x 是 1
if 修饰符
语法
code if condition
如果 conditional 为真,则执行 code。
实例
#!/usr/bin/ruby
$debug=1
print "debug\n" if $debug
这将产生以下结果:
debug
unless 语句
语法
unless conditional [then]
code
[else
code ]
end
unless式和 if式作用相反,即如果 conditional 为假,则执行 code。如果 conditional 为真,则执行 else 子句中指定的 code。
实例
#!/usr/bin/ruby
x=1
unless x>2
puts "x 小于 2"
else
puts "x 大于 2"
end
这将产生以下结果:
x 小于 2
unless 修饰符
语法
code unless conditional
如果 conditional 为假,则执行 code。
实例
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
$var = 1
print "1 -- 这一行输出\n" if $var
print "2 -- 这一行不输出\n" unless $var
$var = false
print "3 -- 这一行输出\n" unless $var
这将产生以下结果:
1 -- 这一行输出
3 -- 这一行输出
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 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
# -*- 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
这将产生以下结果:
小孩