Ruby 提供标准的 control-flow(if、case、)但具有独特、富有表现力的特性:()、、强大的 ,以及更倾向于而非传统循环。Ruby 中的 control flow 读起来很自然。
whiledo_x if conditionunlesscase/whenif age >= 18
puts "adult"
elsif age >= 13
puts "teen"
else
puts "child"
end
# MODIFIER form — condition at the END (reads like English, idiomatic for short cases)
puts "adult" if age >= 18
puts "minor" unless age >= 18 # `unless` = if not (more readable than `if !`)
# everything is an expression — if returns a value
grade = if score >= 90 then "A" else "B" end
Ruby 的modifier 形式(puts "x" if condition)将条件放在末尾,可以编写简洁、可读的单行代码。unless(= "if not")读起来比否定更自然。而且 if 是一个表达式,可以返回一个值。
case status
when :active then "running"
when :stopped, :paused then "halted" # multiple values
when 1..10 then "small number" # ranges
when String then "it's a string" # types (uses ===)
else "unknown"
end
# case can also do structural pattern matching (Ruby 3)
case data
in { name: String => name, age: Integer } # pattern matching with destructuring
puts name
end
Ruby 的**case/when**很强大——它可以匹配值、范围、类型,以及(在 Ruby 3 中)结构模式,在底层使用 ===。比基本的 switch 灵活得多。
while count < 10 do count += 1 end
until done do ... end # until = while not
# ✅ but Ruby PREFERS iteration with blocks over explicit loops:
5.times { |i| puts i } # instead of a for loop
[1, 2, 3].each { |n| puts n } # iterate a collection
(1..10).each { |n| ... } # iterate a range
1.upto(5) { |i| ... }
Ruby 有 while/until,但地道的 Ruby 更倾向于使用 blocks 进行迭代(each、times、map)而非显式循环——更富表现力,更具 Ruby 风格。
理解 Ruby 的 control flow 是每天都需要的基础知识,几个独特的特性反映了 Ruby 注重表现力和可读性的哲学。
modifier 形式(do_x if condition)和**unless**(= "if not")让你可以编写简洁、类似英语的条件语句,这是地道的 Ruby 写法,随处可见。
if 是一个表达式(返回一个值)这一事实让优雅的赋值成为可能。
Ruby 的**case/when**特别强大——通过 === 匹配值、范围、类型和(在 Ruby 3 中)结构模式——使其比基本的 switch 灵活得多,对于清晰的多路分支很有用。
至关重要的是,地道的 Ruby 更倾向于使用 blocks 进行迭代(each、times、map、upto)而非传统的 for/while 循环——这是一个决定性的风格特点:Ruby 开发者用基于 block 的方法迭代集合和范围,而不是使用显式循环,这样更富表现力,更具 Ruby 风格。
理解这些构造和习语——用于可读条件的 modifier 形式和 unless、强大的 case/when,尤其是倾向于基于 block 的迭代而非显式循环——对于编写和阅读地道的 Ruby 代码很重要。
由于 control flow 出现在每个程序中,而且因为 Ruby 的富有表现力的形式(modifiers、unless、强大的 case、block 迭代)体现了其以可读性为中心的哲学,掌握它们是编写自然、地道的 Ruby 代码的必要、基础性知识,而不是从其他语言翻译循环密集的模式。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠