是否有一种简短的方法来编写以下内容(以便x
只出现一次)?
x == nil or x == something
重要的是,当something
满足时,不会调用x == nil
。 x
false
的可能性不需要考虑。
答案 0 :(得分: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解决方案似乎是最快的。