新聞中心
Ruby 提供了其他現(xiàn)代語言中很常見的條件結構。在這里,我們將解釋所有的條件語句和 Ruby 中可用的修飾符。

天橋網(wǎng)站建設公司創(chuàng)新互聯(lián),天橋網(wǎng)站設計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為天橋1000多家提供企業(yè)網(wǎng)站建設服務。企業(yè)網(wǎng)站搭建\外貿(mào)營銷網(wǎng)站建設要多少錢,請找那個售后服務好的天橋做網(wǎng)站的公司定做!
if...else 語句
語法
if conditional [then]
code...
[elsif conditional [then]
code...]...
[else
code...]
endif 表達式用于條件執(zhí)行。值 false 和 nil 為假,其他值都為真。請注意,Ruby 使用 elsif,不是使用 else if 和 elif。
如果 conditional 為真,則執(zhí)行 code。如果 conditional 不為真,則執(zhí)行 else 子句中指定的 code。
通常我們省略保留字 then 。若想在一行內(nèi)寫出完整的 if 式,則必須以 then 隔開條件式和程式區(qū)塊。如下所示:
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
if 修飾符
語法
code if condition
如果 conditional 為真,則執(zhí)行 code。
實例
#!/usr/bin/ruby $debug=1 print "debug\n" if $debug
嘗試一下 ?
這將產(chǎn)生以下結果:
debug
unless 語句
語法
unless conditional [then] code [else code ] end
unless式和 if式作用相反,即如果 conditional 為假,則執(zhí)行 code。如果 conditional 為真,則執(zhí)行 else 子句中指定的 code。
實例
#!/usr/bin/ruby x=1 unless x>2 puts "x 小于 2" else puts "x 大于 2" end
嘗試一下 ?
這將產(chǎn)生以下結果:
x 小于 2
unless 修飾符
語法
code unless conditional
如果 conditional 為假,則執(zhí)行 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
嘗試一下 ?
這將產(chǎn)生以下結果:
1 -- 這一行輸出 3 -- 這一行輸出
case 語句
語法
case expression [when expression [, expression ...] [then] code ]... [else code ] end
case先對一個 expression 進行匹配判斷,然后根據(jù)匹配結果進行分支選擇。
它使用 ===運算符比較 when 指定的 expression,若一致的話就執(zhí)行 when 部分的內(nèi)容。
通常我們省略保留字 then 。若想在一行內(nèi)寫出完整的 when 式,則必須以 then 隔開條件式和程式區(qū)塊。如下所示:
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嘗試一下 ?
這將產(chǎn)生以下結果:
小孩
當前標題:創(chuàng)新互聯(lián)Ruby教程:Ruby 條件判斷
網(wǎng)頁URL:http://www.fisionsoft.com.cn/article/cdsdhpi.html


咨詢
建站咨詢
