Last active
August 29, 2015 14:14
-
-
Save rhearnorth/6989210dcf739e29ff10 to your computer and use it in GitHub Desktop.
Underscorize Hash
This file contains 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' | |
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 |
Author
rhearnorth
commented
Jan 28, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment