萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 條件判斷語句全解析:if、unless、case 與修飾符用法

條件判斷是程式設計的核心邏輯構建塊。Ruby 提供了豐富且具表達力的條件語句,包括 if/else/elsif、unless、case 以及獨特的修飾符語法。本文將系統梳理各類條件語句的語法、特性與實戰範例。

if...else 語句

基本語法:

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

關鍵特性:

  • 在 Ruby 中,只有 false 和 nil 為假值,其他所有物件(包括 0、空字串、空陣列)皆為真值。
  • 關鍵字是 elsif(非 else if 或 elif)。
  • 若條件後緊接保留字,需用換行或分號分隔程式碼。

範例:

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

if 修飾符

單行寫法,適合簡單條件:

code if condition

範例:

#!/usr/bin/ruby
$debug = 1
print "debug\n" if $debug
# 輸出: debug

unless 語句

unless 是 if not 的語法糖,條件為假時執行主體:

unless conditional [then]
  code
[else
  code ]
end

範例:

#!/usr/bin/ruby
x = 1
unless x > 2
  puts "x is less than 2"
else
  puts "x is greater than 2"
end
# 輸出: x is less than 2

unless 修飾符

code unless conditional

範例:

#!/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
# 輸出:
# 1 -- Value is set
# 3 -- Value is set

case 語句

Ruby 的 case 使用 === 運算子進行比對,功能強大且靈活:

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

範例——年齡分級:

#!/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
# 輸出: little child

case 也可用於類別比對、正則比對等進階場景,是處理多重分支的優雅選擇。

copyright © 萬盛學電腦網 all rights reserved