欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳細(xì)解讀Ruby當(dāng)中的條件判斷語句

 更新時(shí)間:2015年05月12日 10:14:33   投稿:goldensun  
這篇文章主要介紹了詳細(xì)解讀Ruby當(dāng)中的條件判斷語句,if、else等邏輯判斷語句是各門編程語言的基礎(chǔ),需要的朋友可以參考下

 Ruby的提供有條件結(jié)構(gòu),常見在現(xiàn)代編程語言中。在這里,我們將解釋Ruby所有條件語句和修飾符
Ruby if...else 語句:
語法:

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

if 表達(dá)式用于條件執(zhí)行。值為false和nil都是假的,其它的都是true。注意Ruby串使用的是elsif,不是else if也不是elif。

if 條件為ture則執(zhí)行代碼。如果條件不為ture,那么將執(zhí)行else子句中指定的代碼。

if 表達(dá)式的條件是保留字,那么,一個(gè)換行符或分號分開代碼。
實(shí)例:

#!/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條件為真執(zhí)行代碼。
實(shí)例:

#!/usr/bin/ruby

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

這將產(chǎn)生以下結(jié)果:

debug

Ruby unless 語句:
語法:

unless conditional [then]
  code
[else
  code ]
end

如果條件為false,執(zhí)行代碼。如果條件是false,else子句中指定的代碼被執(zhí)行。
例如:

#!/usr/bin/ruby

x=1
unless x>2
  puts "x is less than 2"
 else
 puts "x is greater than 2"
end

這將產(chǎn)生以下結(jié)果:

x is less than 2

Ruby unless 修辭符:
語法:

code unless conditional

執(zhí)行代碼,如果有條件的話為false。
實(shí)例:

#!/usr/bin/ruby

$var = 1
print "1 -- Value is set\n" if $var
print "2 -- Value is set\n" unless $var

$var = false
print "3 -- Value is set\n" unless $var

這將產(chǎn)生以下結(jié)果:

1 -- Value is set
3 -- Value is set

Ruby case 語句
語法:

case expression
[when expression [, expression ...] [then]
  code ]...
[else
  code ]
end

比較表達(dá)式指定的情況下,使用===運(yùn)算符時(shí),按指定的條款相匹配時(shí)執(zhí)行的代碼。

子句計(jì)算 when 與左操作數(shù)指定的表達(dá)式。如果沒有子句匹配時(shí),情況下執(zhí)行的代碼else子句。

when 語句的表達(dá)保留字,那么,一個(gè)換行符或分號分開代碼。

那么:

case expr0
when expr1, expr2
  stmt1
when expr3, expr4
  stmt2
else
  stmt3
end

基本上類似于以下內(nèi)容:

_tmp = expr0
if expr1 === _tmp || expr2 === _tmp
  stmt1
elsif expr3 === _tmp || expr4 === _tmp
  stmt2
else
  stmt3
end

實(shí)例:

#!/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

這將產(chǎn)生以下結(jié)果:

little child

相關(guān)文章

最新評論