---
title: "ruby 中尽量少于nil？"
author: "fei1985"
date: "2009-10-31T20:14:31Z"
tags: []
slug: "ruby-nil"
draft: false
lastmod: "2009-10-31T20:19:44Z"
id: 507898
url: "https://1985.iteye.com/blog/507898"
---

ruby是灵活的，同样的效果花的代价却是不同的请看下面的例子：

 

```
require 'benchmark'

Benchmark.bm do|b|

  b.report("without .nil?") do
    cat = nil
    bat = 'vampire'
    2_000_000.times do
      unless bat        
        true if cat
      end
    end
  end
  
  
  b.report("with nil? ") do
    cat = nil
    bat = 'vampire'
    2_000_000.times do
      unless bat.nil?
        true unless cat.nil?        
      end
    end
  end

end
```

 在我的电脑上测试结果如下：

      user     system      total        real  
without .nil?  0.390000   0.000000   0.390000 (  0.392000)  
with nil?   1.014000   0.000000   1.014000 (  1.024000)

 

所以说我们在一些情况下用unless来代替nil?

```
do_something unless user
或者
unless user
  do_something
end
```