Preface
case 就類似其它語言(如C/C++、Java)經常會提供的 switch..case,一個使用的例子如下:
- # encoding: Big5
- print "請輸入分數:"
- case gets.to_i / 10
- when 10, 9
- puts "等級 A"
- when 8
- puts "等級 B"
- when 7
- puts "等級 C"
- when 6
- puts "等級 D"
- else
- puts "等級 E"
- end
case...when...else
在 when 比對成功時執行的程式碼若要撰寫在同一行,必須使用 then。例如:
- # encoding: Big5
- print "請輸入分數:"
- case gets.to_i / 10
- when 10, 9 then puts "等級 A"
- when 8 then puts "等級 B"
- when 7 then puts "等級 C"
- when 6 then puts "等級 D"
- else puts "等級 E"
- end
- # encoding: Big5
- print "請輸入分數:"
- puts case gets.to_i / 10
- when 10, 9 ; "等級 A"
- when 8 ; "等級 B"
- when 7 ; "等級 C"
- when 6 ; "等級 D"
- else ; "等級 E"
- end
case 比對每次遇到 when 時,就會拿 case 右邊設定的物件,與 when 設定的物件進行 === 比對,若結果為 true,表示比對成功,所以實際上完整寫法如下:
- # encoding: Big5
- print "請輸入分數:"
- n = gets.to_i / 10
- puts case n
- when n === 10, n === 9 ; "等級 A"
- when n === 8 ; "等級 B"
- when n === 7 ; "等級 C"
- when n === 6 ; "等級 D"
- else ; "等級 E"
- end
- # encoding: Big5
- print "請輸入分數:"
- n = gets.to_i / 10
- # 以下寫法是錯的
- puts case n
- when n == 10, n == 9 ; "等級 A"
- when n == 8 ; "等級 B"
- when n == 7 ; "等級 C"
- when n == 6 ; "等級 D"
- else ; "等級 E"
- end
- # encoding: Big5
- print "請輸入分數:"
- n = gets.to_i / 10
- puts case
- when n == 10, n == 9 ; "等級 A"
- when n == 8 ; "等級 B"
- when n == 7 ; "等級 C"
- when n == 6 ; "等級 D"
- else ; "等級 E"
- end
- class Array
- def comprehend(&block)
- return self if block.nil?
- self.collect(&block).compact
- end
- end
- def quick(lst)
- case
- when lst.length <= 1
- return lst
- when pivot = lst.shift
- printf "Pivot=%s:\n", pivot
- before = lst.comprehend { |i| i if i < pivot}
- printf "\tBefore=%s\n", before
- after = lst.comprehend { |i| i if i >= pivot}
- printf "\tAfter=%s\n", after
- merge=quick(before) + [pivot] + quick(after)
- printf "\tMerge=%s\n", merge
- return merge
- else
- printf "\t[Error] Unknown case!\n"
- end
- end
- ary = [1,4,5,3,8,9,7,2,6]
- printf "ary=#{ary} (%s)\n", ary.class
- print "Quick sort...\n"
- ary=quick(ary)
補充說明:
* Array.collect: Invokes the given block once for each element of self.
* Array.compact: Returns a copy of self with all nil elements removed.
沒有留言:
張貼留言