2014-10-31 22 views
-3

有没有简短的方法来写下面的(这样x只出现一次)?检查是否有一些falsy值或什么

x == nil or x == something 

一个重要的事情是,当x == nil满足调用something没有这样做。不需要考虑xfalse的可能性。

+0

在这种情况下,'x ==(nil || something)'不会起作用吗?或者我误解了你的问题? – Surya 2014-10-31 09:30:26

+1

@ User089247'x ==(nil || something)'相当于'x == something'。 – 2014-10-31 09:39:06

+0

@MarekLipka:谢谢。然后我看不到检查'x == nil'的问题。 – Surya 2014-10-31 09:57:08

回答

0

而不是x == nil你可以测试x.nil?

所以,你可以使用:

x.nil? or x == something 

x.nil? || x == something 

include?需要额外的阵列的解决方案,根据您的报告可能需要一些额外的工作量(但我认为这是不必要的微调)

不过,这是一个基准:

require 'benchmark' 

TEST_LOOPS = 10_000_000 
X = nil 
Y = :something 
Z = :something_else 

Benchmark.bm(20) {|b| 

    b.report('nil? or') { 
    TEST_LOOPS.times { 
     X.nil? or X == :something 
     Y.nil? or Y == :something 
     Z.nil? or Z == :something 
    }   #Testloops 
    }    #b.report 

    b.report('nil? ||') { 
    TEST_LOOPS.times { 
     X.nil? || X == :something 
     Y.nil? || Y == :something 
     Z.nil? || Z == :something 
    }   #Testloops 
    } 

    b.report('== nil or') { 
    TEST_LOOPS.times { 
     X== nil or X == :something 
     Y== nil or Y == :something 
     Z== nil or Z == :something 
    }   #Testloops 
    }    #b.report 

    b.report('== nil ||') { 
    TEST_LOOPS.times{ 
     X== nil || X == :something 
     Y== nil || Y == :something 
     Z== nil || Z == :something 
    }   #Testloops 
    }    #b.report 

    #Only if X being false does not need to be considered. 
    b.report('!X ||') { 
    TEST_LOOPS.times{ 
     !X || X == :something 
     !Y || Y == :something 
     !Z || Z == :something 
    }   #Testloops 
    }    #b.report 

    b.report('include?') { 
    TEST_LOOPS.times { 
     [nil, :something].include?(X) 
     [nil, :something].include?(Y) 
     [nil, :something].include?(Z) 
    }   #Testloops 
    } 

    b.report('include? precompile') { 
    testarray = [nil, :something] 
    TEST_LOOPS.times { 
     testarray.include?(X) 
     testarray.include?(Y) 
     testarray.include?(Z) 
    }   #Testloops 
    } 
} #Benchmark 

我的结果是:在评论

      user  system  total  real 
nil? or    2.574000 0.000000 2.574000 ( 2.574000) 
nil? ||    2.543000 0.000000 2.543000 ( 2.542800) 
== nil or    2.356000 0.000000 2.356000 ( 2.355600) 
== nil ||    2.371000 0.000000 2.371000 ( 2.371200) 
!X ||     1.856000 0.000000 1.856000 ( 1.856400) 
include?    4.477000 0.000000 4.477000 ( 4.477200) 
include? precompile 2.746000 0.000000 2.746000 ( 2.745600) 

Stefans解决方案似乎是最快的。

相关问题