流程控制

流程控制

if

a = 2 if some_condition

if 1 > 2
  3
else
  nil
end

## 三元玩法
a = 1 > 2 ? 3 : 4

a = if 1 > 2 # if作为表达式直接给变量赋值
      3
    else
      4
    end

if a = some_expression
  # here a is not nil
end

if a && b
  # here both a and b are guaranteed not to be Nil
end

## if表达式判断对于类和对象的属性无效
## 方法一: 需要先将属性值赋给一个本地变量
if a = @a
  # here a can't be nil
end

## 方法二: use `Object#try` found in the standard library
@a.try do |a|
  # here a can't be nil
end

if var.is_a?(...)  # 判断var的类型是否是参数指定的类型
if a.is_a(Number) && if a.is_a(String)

if var.responds_to?(...) # 判断var是否具有参数指定的方法
if a.responds_to(:abs )

if var.nil? # 判断var是否为空

if !
if !b.is_a?(Int32)

unless

同if相反

unless some_condition
  then_expression
else
  else_expression
end

case

…略,请自行参阅

while

支持next ,break进行控制

while some_condition
  if condition1
    next
  end

  do_this
  if condition
    break
  end

end

util

…略

&& , ||

可用于链式操作

some_exp1 || some_exp2
some_exp1 && some_exp2