Skip to content

Instantly share code, notes, and snippets.

@solnic
Forked from tenderlove/test.rb
Created January 12, 2012 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solnic/1600001 to your computer and use it in GitHub Desktop.
Save solnic/1600001 to your computer and use it in GitHub Desktop.
# encoding: utf-8
require 'rubygems'
require 'benchmark/ips'
require 'set'
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
BOOLEAN_MAP = Hash[ %w[ 1 on t true y yes ].product([ true ]) ]
def original value
if value.is_a?(String) && value.empty?
nil
else
TRUE_VALUES.include?(value)
end
end
def regexp value
case value
when String
value =~ /^(?:1|t(?:rue)?)$/i
when true, 1
true
else
false
end
end
def boolean_map(value)
BOOLEAN_MAP.fetch(value.downcase, value)
end
n = 50000
Benchmark.ips do |x|
x.report('original hit') {
original 'true'
}
x.report('original miss') {
original 'false'
}
x.report('regex hit') {
regexp 'true'
}
x.report('regex miss') {
regexp 'false'
}
x.report('boolean_map hit') {
original 'TrUE'
}
x.report('boolean_map miss') {
original 'FaLSE'
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment