標籤:if case unless
=begin 條件判斷語句包括if語句,unless語句,case語句,=end#if 語句=beginif 條件 then 處理1elsif 條件2 then 處理2else 處理3end=enda = 10b = 20if a > b puts "a bigger than b"elsif a < b puts "a smaller than b"else puts "a is equal to b"endputs "a bigger than b" if a > b#unless 語句,與if語句相反,條件判斷為假的時執行處理=beginunless 條件 處理1else 處理2end=enda = 10b = 20unless a > b puts "a smaller/same as than b"end#case 語句,適用於比較的對象只有一個的時候,根據這個對象的值不同,執行不同的處理;when可以一次指定多個值=begincase 比較對象when 值1 then 處理1when 值2 then 處理2when 值3 then 處理3else 處理4end=endtags = ["A", "IMG", "PRE"]tags.each do |word| case word when "P", "A", "I", "B", "BLOCKQUOTE" puts "#{word} has child." when "IMG", "BR" puts "#{word} has child." else puts "#{word} cannoot be used" endendarray = ["a", 1, nil]array.each do |word| case word when String puts "the word is a String" when Numeric puts "the word is a Numeric" else puts "other words are Something" endendtext.each_line do |line| case line when /^From:/i puts "find a sender" when /^To:/i puts "find a receiver" when /^$/ puts "resolution are finnished" exit else break endend
本文出自 “邀月乘風” 部落格,請務必保留此出處http://yaoyuechengfeng.blog.51cto.com/2958475/1774804
Ruby-條件判斷