如果您控制哈希的内容,并且它相对较小,我会在私有方法中使用这样的东西作为通用解决方案。
def exclusively_true?(hash, key)
return false unless hash.delete(key) == true
!hash.has_value? true
end
require 'test/unit'
class TestExclusive < Test::Unit::TestCase
def setup
@test_hash = {foo: true, bar: false, hoge: false}
end
def test_exclusive
assert_equal(true, exclusively_true?(@test_hash, :foo))
end
def test_inexclusive
@test_hash[:bar] = true
assert_equal(false, exclusively_true?(@test_hash, :foo))
end
end
require 'benchmark'
h = {foo: true}
999.times {|i| h["a#{i}"] = false}
Benchmark.bmbm(30) do |x|
x.report('exclusively_true') do
1000.times do
exclusively_true?(h, :foo)
end
end
end
人为的基准测试:(OS X 10.8.3 / 3 GHz / 8 GB)
ruby -v: ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-darwin12.3.0]
Rehearsal ------------------------------------------------------------------
exclusively_true 0.000000 0.000000 0.000000 ( 0.000412)
--------------------------------------------------------- total: 0.000000sec
user system total real
exclusively_true 0.000000 0.000000 0.000000 ( 0.000331)