3.9 條件判斷語句

判斷條件是否相等用“==”,注意不要寫成“=”。
一. 單行 if(如果) 語句
1)        if    條件 then 語句1; 語句2 ; 語句… end
2)        語句1; 語句2 ; 語句   if   條件
 
. 多行 if 語句
if 條件
       語句1; 語句2 ; 語句
elsif 條件
       語句1; 語句2 ; 語句
else
       語句1; 語句2 ; 語句
end
 
三. unless(除非) 條件語句:
  unless 條件 = if not (條件)       
 
四. case分支條件語句
看程序 E3.9-1.rb
 
case 對象
when 可能性1
語句1; 語句2 ; 語句
when 可能性2
語句1; 語句2 ; 語句
when 可能性
語句1; 語句2 ; 語句
else
語句1; 語句2 ; 語句
end
 
例:x=3
case x
 when 1..2
    print "x=",x,"; 1..2"
 when 4..9, 0
    print "x=",x,";4..9,0,或是0"
 else
    print "x=",x,";其它可能"
end
結果:x=3;其它可能
 
 

Ruby裏,nil 和 false 爲假,其它都爲真;例如:
                                                      puts "is true"  if  5    #=>is true
                                     str="false"; puts "is true"  if str   #=>is true

完整閱讀,請看我寫的 Ruby語言中文教程all in one    
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章