條件判斷,在編程語言中都存在,而Ruby中的條件判斷和Java中類似,當然還是存在些許差別
Ruby中條件判斷的條件:
1) 可以使用 ==,<,>等比較運算來作為條件,比較運算可以返回true和false,這和java中的語法是類似的
2) 一些其他的方法也可以用來作為判斷條件,比如,empty?方法,為空則返回true,否則返回false
3) 有些方法雖然不會返回true或false,但是也能作為條件判斷的條件,他們返回的對象,要麼是false或nil,要麼是意義的對象,則可根據如下表格判斷:
TRUE | FALSE |
false和nil以外的對象 | false與nil |
p /Ruby/ =~ "Ruby" 返回0,則在條件判斷中可以返回true
Ruby中也可以使用常用的邏輯運算符,&&,||,!,其代表的意義與JAVA中的意義是一致的。
Ruby中的條件判斷語句:
1. if 語句
=begin
語法:
if 條件1 then
語句1
elsif 條件2 then
語句2
elsif 條件3 then
語句3
else
語句4
end
=end
a = 10
b = 20
if a>b then
print "a is smaller than b."
elsif a == b then
print "a equals b."
else
print "a is larger than b."
end
2. unless 語句,其恰好與if語句相反,當條件不符合時,則執行相應語句
=begin
語法:
unless 條件 then
語句
end
=end
a = 10
b = 20
unless a>b then
print "a is smaller than b."
end
# -> "a is smaller than b" will be printed out.
3. case 語句
當同一個對象,要與多個值進行比較時,可以使用case語句,其功能與JAVA中的switch語句類似
=begin
語法:
case 想要比較的對象
when 值1 then
語句1
when 值2 then
語句2
when 值3 then
語句3
else
語句4
end
# then是可以省略的
=end
array = ["aa", 1, nil]
item = array[0]
case item
when String
puts "item is a String."
when Numeric
puts "item is a Numeric."
else
puts "item is a something"
end
#這裡比較的是對象的類型,而不是對象的值
PS:
if修飾符和unless修飾符可以寫在執行語句後面,例如,print "a is larger than b." if a>b,所以ruby是很靈活的。
"==="符號的意義,其在不同的場合可以代表不同的符號,若左邊是數字或字元串時,則和"=="是一樣的;在正則表達式的場合下則相當於"=~";在類的場合下,判斷"==="右邊的對象是否是類的實例
p ((1..3) === 2) #-> true
p /zz/ === "zyzzy" #-> 2
p String === "xyzzy" # -> true
#在case表達與if語句間轉換,用===,符號左邊是case的值,右邊為case的變數
case A
when value1 if value1 === A
語句1 語句1
when value2 elsif value2 === A
語句2 語句2
else else
語句3 語句3
end end