2011-07-05 46 views

回答

1

雖然這兩個操作是非常不同的我很確定他們總是會產生相同的結果。 (一種叫做NilClass對象的#nil?方法,另一種叫做nil單身人士。)

我會建議,如果有人懷疑你走第三條路,實際上只是測試表達式的真值。

所以,if x和不if x == nilif x.nil?,爲了具有該測試DTRT當表情值

2

有一個區別:一個類可能定義零?是真的:

class X 
    def nil?() 
    true 
    end 
end 

puts X.new.nil? #-> true 

還是一個實際的例子(我不推薦它,如果你需要的話,我會定義一個nil_or_empty?):

class String 
    def nil?() 
    return empty? 
    end 
end 

puts 'aa'.nil? #-> false 
puts ''.nil? #-> true 

運行基準爲零?似乎要快一點。

require 'benchmark' 

TEST_LOOPS = 100_000_000 

C_A = nil 
C_B = 'aa' 

Benchmark.bmbm(10) {|b| 

    b.report('nil?') { 
    TEST_LOOPS.times { 
     x = C_A.nil? 
     x = C_B.nil? 
    }   #Testloops 
    } 
    b.report('==nil') { 
    TEST_LOOPS.times { 
     x = (C_A == nil) 
     x = (C_B == nil) 
    }   #Testloops 
    }    #b.report 

} #Benchmark 

結果:

Rehearsal --------------------------------------------- 
nil?  27.454000 0.000000 27.454000 (27.531250) 
==nil  31.000000 0.000000 31.000000 (31.078125) 
----------------------------------- total: 58.454000sec 

       user  system  total  real 
nil?  27.515000 0.000000 27.515000 (27.546875) 
==nil  31.125000 0.000000 31.125000 (31.171875) 
+1

這可能是一個非常糟糕的主意重新實現''爲零,因爲它會導致各種混亂的? – tadman

+2

你可以重新實現'=='(和相關的方法),這樣'X.new == nil'返回true。 –

+0

你是對的 - ruby​​總是比預期的更靈活;) – knut