邏輯判斷
在 Ruby 裡,只有兩個東西是假的: nil 和 false,其他都是真的。
在寫程式的時候,你需要想的比電腦多,如果你不把所有可能性包含進去,電腦遇到你沒說的場景,就會直接停住不動,所以流程控制是很重要的!
以下是 ruby 幾種常見的流程控制寫法:
if ……如果
weather = "下雨"
if weather == "下雨"
puts "待在家"
end
#和下列程式相等,倒裝句,如果只有一行
puts "待在家" if weather == "下雨"
if …. else 二分法
weather = "下雨"
if weather == "下雨"
puts "待在家"
else
puts "粗乃玩"
end
三元運算子:如果是 true 就走前面的路,如果是 false 就走 ":"後面那條。
#原本的 if ... elseage = "19"
if age >= 18
status = "已成年"
else
status = "未成年"
end
#改成三元運算子
status = (age >= 18) ? "已成年" : "未成年"
更多的選擇:if … elsif … else 或使用 case … when
weather = "下雨"
if weather == "下雨"
puts "待在家"
elsif weather == "出太陽"
puts "粗乃玩"
else
puts "睡覺"
end
#其他的寫法-看起來更有結構
weather = "下雨"
case weather
when "下雨"
puts "待在家"
when "出太陽"
puts "粗乃玩"
else
puts "睡覺"
end
例外處理: begin ….rescue
例外不代表錯誤,所以如果用 if … else 不一定會處理,只有 nil 或 false , if 才會判定是 false 改成 else 路徑,所以如果要避免例外,建議用 begin … rescue 。
def bmi_calculator(height, weight)
begin
weight / (height * height)
rescue
puts "你輸入的號碼有誤"
end
end
#簡化寫法
def bmi_calculator(height, weight)
weight / (height * height)
rescue => exception
"你輸入的號碼有誤"
end