Latest web development tutorials

Ruby 條件判斷

Ruby 提供了幾種很常見的條件結構。 在這裡,我們將解釋所有的條件語句和Ruby 中可用的修飾符。

Rubyif...else語句

語法

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

if表達式用於條件執行。 值falsenil為假,其他值都為真。 請注意,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

Rubyif修飾符

語法

code if condition

if修飾詞組表示當if 右邊之條件成立時才執行if 左邊的式子。 即如果conditional為真,則執行code

實例

#!/usr/bin/ruby

$debug=1
print "debug\n" if $debug

以上實例輸出結果:

debug

Rubyunless語句

語法

unless conditional [then]
   code
[else
   code ]
end

unless式和if式作用相反,即如果conditional為假,則執行code。 如果conditional為真,則執行else子句中指定的code

實例

#!/usr/bin/ruby
# -*- coding: UTF-8 -*-

x=1
unless x>2
   puts "x 小于 2"
 else
  puts "x 大于 2"
end

以上實例輸出結果為:

x 小于 2

Rubyunless修飾符

語法

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 -- 这一行输出

Rubycase語句

語法

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

以上實例輸出結果為:

小孩

當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"