2014-10-31 3 views
-3

다음을 쓸 수있는 간단한 방법이 있습니까? (x이 한 번만 나타납니다)?위변조 값인지 아닌지 확인

x == nil or x == something 

중요한 것은 x == nil이 만족할 때 something를 호출하는 것은 수행되지 않는 것입니다. xfalse 일 가능성은 고려할 필요가 없습니다.

+0

이 경우'x == (nil || something)'이 작동하지 않습니까? 아니면 당신의 질문을 오해 했나요? – Surya

+1

@ User089247'x == (nil || something)'은'x == something'과 동일합니다. –

+0

@MarekLipka : 감사합니다. 그렇다면'x == nil'인지 검사 할 점이 없습니다. – Surya

답변

0

x == nil 대신 x.nil?을 테스트 할 수 있습니다.

x.nil? or x == something 

또는

x.nil? || x == something 

추가 배열을 필요로 include?와 솔루션이 보고서에 따라이 몇 가지 추가 작업을해야 할 수도 있습니다 (하지만 난 그게 필요하다고 생각 :

그래서 당신은 사용할 수 있습니다

: microtuning)

그럼에도 불구하고

, 여기에 벤치 마크입니다

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 솔루션은 빠른 것 같다.

관련 문제