Ruby簡明教程之判斷語句介紹_ruby專題

來源:互聯網
上載者:User

條件判斷,在程式設計語言中都存在,而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是很靈活的。

"==="符號的意義,其在不同的場合可以代表不同的符號,若左邊是數字或字串時,則和"=="是一樣的;在Regex的場合下則相當於"=~";在類的場合下,判斷"==="右邊的對象是否是類的執行個體

複製代碼 代碼如下:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.