Created
May 24, 2011 18:24
-
-
Save LTe/989313 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
require 'strscan' | |
n = 100000 | |
u = "hello_world/whatever" | |
class String | |
# From rails | |
def camelize | |
self.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase } | |
end | |
# From merb | |
def mamelize | |
new_string = "" | |
input = StringScanner.new(self.downcase) | |
until input.eos? | |
if input.scan(/([a-z][a-zA-Z\d]*)(_|$|\/)/) | |
new_string << input[1].capitalize | |
new_string << "::" if input[2] == '/' | |
end | |
end | |
new_string | |
end | |
def lamelize | |
self.split('/').map { |ss| ss.split('_').map { |sub| sub.capitalize }.join }.join('::') | |
end | |
def damelize | |
self.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } | |
end | |
end | |
puts u.camelize | |
puts u.mamelize | |
puts u.lamelize | |
puts u.damelize | |
Benchmark.bm do |x| | |
x.report("Camelize") do | |
n.times { u.camelize } | |
end | |
x.report("Mamelize") do | |
n.times { u.mamelize } | |
end | |
x.report("Lamelize") do | |
n.times { u.mamelize } | |
end | |
x.report("Damelize") do | |
n.times { u.damelize } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment