考虑以下:
response = responses.to_a.first
这将返回的第一个元素responses,或nil。然后,因为条件语句nil就像false我们可以这样写:
response = responses.to_a.first
if response
  # do something ('happy path')
else
  # do something else
end
比以下内容更具可读性:
if response.nil?
  # do something else
else
  # do something ('happy path')
end
该if (object)模式在Ruby代码中非常常见。它还可以很好地导致重构,例如:
if response = responses.to_a.first
  do_something_with(response)
else
  # response is equal to nil
end
还要记住,Ruby方法nil默认返回。所以:
def initial_response
  if @condition
    @responses.to_a.first
  else
    nil
  end
end
可以简化为:
def initial_response
  if @condition
    @responses.to_a.first
  end
end
因此,我们可以进一步重构:
if response = initial_response
  do_something_with(response)
else
  # response is equal to nil
end
现在您可以辩称,返回nil并不总是最好的主意,因为这意味着检查nil所有地方。但这是另一锅鱼。鉴于测试对象“存在或不存在”的需求如此频繁,因此对象的真实性是Ruby的一个有用方面,尽管对于使用该语言的新手来说是令人惊讶的。