Skip to content

Instantly share code, notes, and snippets.

@rhearnorth
Last active August 29, 2015 14:14
Show Gist options
  • Save rhearnorth/6989210dcf739e29ff10 to your computer and use it in GitHub Desktop.
Save rhearnorth/6989210dcf739e29ff10 to your computer and use it in GitHub Desktop.
Underscorize Hash
require 'benchmark'
Benchmark.bmbm do |x|
HASH_TEST = {'a' => 'a', 'b' => { 'c' => {'firstName' => 'd'}, 'e' => 'e'}}
def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
when Hash
Hash[value.map { |k, v| [underscore_key(k), convert_hash_keys(v)] }]
else
value
end
end
def underscore_key(key)
key.to_s.underscore.to_sym
end
x.report("Helper #convert_hash_keys") do
convert_hash_keys(HASH_TEST)
end
x.report("#transform_keys") do
HASH_TEST.transform_keys{ |key| key.to_s.underscore.to_sym }
end
x.report("#with_indifferent_access") do
HASH_TEST.with_indifferent_access
end
end
@rhearnorth
Copy link
Author

Rehearsal -------------------------------------------------------------
#convert_hash_keys          0.000000   0.000000   0.000000 (  0.000272)
#transform_keys             0.000000   0.000000   0.000000 (  0.000108)
#with_indifferent_access    0.000000   0.000000   0.000000 (  0.000053)
---------------------------------------------------- total: 0.000000sec

                                user     system      total        real
#convert_hash_keys          0.000000   0.000000   0.000000 (  0.000239)
#transform_keys             0.000000   0.000000   0.000000 (  0.000136)
#with_indifferent_access    0.000000   0.000000   0.000000 (  0.000031)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment