# Ruby 判斷
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_。
if 表達式的 _conditional_ 通過保留字 _then_、一個換行符或一個分號,來與代碼分離開。
## 實例
```
#!/usr/bin/ruby
x=1
if x > 2
puts "x is greater than 2"
elsif x <= 2 and x!=0
puts "x is 1"
else
puts "I can't guess the number"
end
```
```
x is 1
```
## Ruby _if_ 修飾符
## 語法
```
code if condition
```
如果 _conditional_ 為真,則執行 _code_。
## 實例
```
#!/usr/bin/ruby
$debug=1
print "debug\n" if $debug
```
這將產生以下結果:
```
debug
```
## Ruby _unless_ 語句
## 語法
```
unless conditional [then]
code
[else
code ]
end
```
如果 _conditional_ 為假,則執行 _code_。如果 _conditional_ 為真,則執行 else 子句中指定的 _code_。
## 實例
```
#!/usr/bin/ruby
x=1
unless x>2
puts "x is less than 2"
else
puts "x is greater than 2"
end
```
這將產生以下結果:
```
x is less than 2
```
## Ruby _unless_ 修飾符
## 語法
```
code unless conditional
```
如果 _conditional_ 為假,則執行 _code_。
## 實例
```
#!/usr/bin/ruby
$var = 1
print "1 -- Value is set\n" if $var
print "2 -- Value is set\n" unless $var
$var = false
print "3 -- Value is set\n" unless $var
```
這將產生以下結果:
```
1 -- Value is set
3 -- Value is set
```
## Ruby _case_ 語句
## 語法
```
case expression
[when expression [, expression ...] [then]
code ]...
[else
code ]
end
```
比較 case 所指定的 _expression_,當使用 === 運算符指定時,執行匹配的 when 子句的 _code_。
when 子句所指定的 _expression_ 背當作左操作數。如果沒有匹配的 when 子句,_case_ 執行 _else_ 子句的代碼。
when 語句的表達式通過保留字 _then_、一個換行符或一個分號,來與代碼分離開。
因此:
```
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
$age = 5
case $age
when 0 .. 2
puts "baby"
when 3 .. 6
puts "little child"
when 7 .. 12
puts "child"
when 13 .. 18
puts "youth"
else
puts "adult"
end
```
這將產生以下結果:
```
little child
```
- Ruby 基礎
- Ruby 簡介
- Ruby 環境
- Ruby 安裝 - Unix
- Ruby 安裝 - Windows
- Ruby 命令行選項
- Ruby 環境變量
- Ruby 語法
- Ruby 數據類型
- Ruby 類和對象
- Ruby 類案例
- Ruby 變量
- Ruby 運算符
- Ruby 注釋
- Ruby 判斷
- Ruby 循環
- Ruby 方法
- Ruby 塊
- Ruby 模塊(Module)
- Ruby 字符串(String)
- Ruby 數組(Array)
- Ruby 哈希(Hash)
- Ruby 日期 & 時間(Date & Time)
- Ruby 范圍(Range)
- Ruby 迭代器
- Ruby 文件的輸入與輸出
- Ruby File 類和方法
- Ruby Dir 類和方法
- Ruby 異常
- Ruby 高級
- Ruby 面向對象
- Ruby 正則表達式
- Ruby 數據庫訪問 - DBI 教程
- Ruby CGI 編程
- Ruby CGI方法
- Ruby CGI Cookies
- Ruby CGI Sessions
- Ruby 發送郵件 - SMATP
- Ruby Socket 編程
- Ruby XML, XSLT 和 XPath 教程
- Ruby Web Services 應用 - SOAP4R
- Ruby 多線程
- 免責聲明