解讀Ruby當中的條件判斷語句
這篇文章主要介紹了詳細解讀Ruby當中的條件判斷語句,if、else等邏輯判斷語句是各門程式設計語言的基礎,需要的朋友可以參考下
Ruby的提供有條件結構,常見在現代程式設計語言中。在這裡,我們將解釋Ruby所有條件陳述式和修飾符
Ruby if...else 語句:
文法:
?
|
1
2
3
4
5
6
7 |
if conditional [then]
code...
[elsif conditional [then]
code...]...
[else
code...]
end
|
if 運算式用於條件執行。值為false和nil都是假的,其它的都是true。注意Ruby串使用的是elsif,不是else if也不是elif。
if 條件為ture則執行代碼。如果條件不為ture,那麼將執行else子句中指定的代碼。
if 運算式的條件是保留字,那麼,一個分行符號或分號分開代碼。
執行個體:
?
|
1
2
3
4
5
6
7
8
9
10
11
12 |
#!/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
if條件為真執行代碼。
執行個體:
?
|
1
2
3
4 |
#!/usr/bin/ruby
$debug=1
print "debugn" if $debug
|
這將產生以下結果:
?
Ruby unless 語句:
文法:
?
|
1
2
3
4
5 |
unless conditional [then]
code
[else
code ]
end
|
如果條件為false,執行代碼。如果條件是false,else子句中指定的代碼被執行。
例如:
?
|
1
2
3
4
5
6
7
8 |
#!/usr/bin/ruby
x=1
unless x>2
puts "x is less than 2"
else
puts "x is greater than 2"
end
|
這將產生以下結果:
?
Ruby unless 修辭符:
文法:
code unless conditional
執行代碼,如果有條件的話為false。
執行個體:
?
|
1
2
3
4
5
6
7
8 |
#!/usr/bin/ruby
$var = 1
print "1 -- Value is setn" if $var
print "2 -- Value is setn" unless $var
$var = false
print "3 -- Value is setn" unless $var
|
這將產生以下結果:
?
|
1
2 |
1 -- Value is set
3 -- Value is set
|
Ruby case 語句
文法:
?
|
1
2
3
4
5
6 |
case expression
[when expression [, expression ...] [then]
code ]...
[else
code ]
end
|
比較運算式指定的情況下,使用===運算子時,按指定的條款相匹配時執行的代碼。
子句計算 when 與左運算元指定的運算式。如果沒有子句匹配時,情況下執行的代碼else子句。
when 語句的表達保留字,那麼,一個分行符號或分號分開代碼。
那麼:
?
|
1
2
3
4
5
6
7
8 |
case expr0
when expr1, expr2
stmt1
when expr3, expr4
stmt2
else
stmt3
end
|
基本上類似於以下內容:
?
|
1
2
3
4
5
6
7
8 |
_tmp = expr0
if expr1 === _tmp || expr2 === _tmp
stmt1
elsif expr3 === _tmp || expr4 === _tmp
stmt2
else
stmt3
end
|
執行個體:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
#!/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
|
這將產生以下結果:
?