Skip to content

Instantly share code, notes, and snippets.

@sivsushruth
Created January 19, 2015 04:24
Show Gist options
  • Save sivsushruth/71cf61472d5c5ba9c9cd to your computer and use it in GitHub Desktop.
Save sivsushruth/71cf61472d5c5ba9c9cd to your computer and use it in GitHub Desktop.
require 'bundler/setup'
require 'active_support/all'
require 'benchmark/ips'
class Hash
def new_transform_keys!
return enum_for(:transform_keys!) unless block_given?
keys.each do |key|
if keys.map(&:to_s).count(key.to_s) == 1
self[yield(key)] = delete(key)
else
delete(key)
end
end
self
end
def new_stringify_keys!
new_transform_keys!(&:to_s)
end
end
Benchmark.ips do |x|
x.time = 5
x.warmup = 2
x.report "stringify_keys!" do
hsh = { surprise: true, 'surprise' => false }
hsh.stringify_keys!
end
x.report "new_stringify_keys!" do
hsh = { surprise: true, 'surprise' => false }
hsh.new_stringify_keys!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment