if..elsif..end / unless..end

Ruby 具有表达式和表达式修饰符形式的标准 if 条件。在所有上下文中,unless condition 完全等效于 if not condition

if/unless 表达式返回其最后一个表达式的值。

块形式

语法

 if condition [then]
   code
 [elsif condition [then]
   code]
 [else

   code]
 end
 unless condition
   code
 [else

   code]
 end

说明

if 的基本表达式形式如下所示,并且必须以 end 结尾:

 if some_condition_expression

   # This section executed if some_condition_expression is true
 end

else 关键字可用于提供在条件表达式的计算结果为 false 时执行的部分。if 表达式中只能包含一个 else

 if some_condition_expression
   # This section executed if some_condition_expression is true
 else

   # This section executed if some_condition_expression is false
 end

elsif 关键字可用于创建多个互斥的条件。如果初始 if 中的条件不为 true,则顺次计算每个 elsif 条件的结果,直到有一个条件为 true 时为止。如果条件均不为 true,则执行 else 部分(如果存在):

 if cond_one

   # cond_one is true
 elsif cond_two
   # cond_one is not true and cond_two is true
 elsif cond_three
   # cond_one is not true and cond_two is not true and cond_three is true
 else
   # cond_one, cond_two and cond_three are all not true
 end

如果使用 unless,则无法定义 elsif,而只能定义 else

其中,if 表达式可能添加了可选的 then 表达式,但通常将其省略。

 if some_condition_expression then
   # ...
 elsif some_other_condition_expression then

   # ...
 end

但是,如果要将 if 表达式放在一行,则必须使用 then 表达式。

 if some_condition_expression then do_something end