Z
ZHANK
控制流程

条件判断

if/elsif/else、unless、case/when(比 switch 强大)、三元运算符

条件判断

Ruby 的条件判断比大多数语言更灵活——unless(反 if)、case/when(比 switch 强大)、修饰符 afterthought。

学完本章你将: 掌握 if/elsif/else、unless、case/when、修饰符。


if / elsif / else

ruby
score = 85

if score >= 90
    puts "优秀"
elsif score >= 80
    puts "良好"    # 输出
else
    puts "加油"
end

unless —— "如果条件为假"

ruby
# unless = if not
unless user.active?
    puts "用户未激活"
end

# 等价于
if !user.active?
    puts "用户未激活"
end

case / when

ruby
case score
when 90..100
    puts "A"
when 80...90
    puts "B"
when 70...80
    puts "C"
else
    puts "D"
end

# case 不传值——更灵活
case
when score >= 90 then puts "A"
when score >= 80 then puts "B"
else puts "C"
end

修饰符 afterthought

ruby
# 条件后置——适合简单语句
puts "ok" if valid
puts "error" unless valid

# 等价于
if valid then puts "ok" end
unless valid then puts "error" end