-
-
Save treble37/9823228 to your computer and use it in GitHub Desktop.
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
source: http://avdi.org/devblog/2009/11/20/hash-transforms-in-ruby/ | |
def transform_hash(original, options={}, &block) | |
original.inject({}){|result, (key,value)| | |
value = if (options[:deep] && Hash === value) | |
transform_hash(value, options, &block) | |
else | |
value | |
end | |
block.call(result,key,value) | |
result | |
} | |
end | |
h = { :foo => 1, :bar => {:baz => 3}, :buz => 4 } | |
h.map{|k,v| [k.to_s, v]} # => [["foo", 1], ["bar", {:baz=>3}], ["buz", 4]] | |
# Convert keys to strings | |
def stringify_keys(hash) | |
transform_hash(hash) {|hash, key, value| | |
hash[key.to_s] = value | |
} | |
end | |
stringify_keys(h) # => {"foo"=>1, "buz"=>4, "bar"=>{:baz=>3}} | |
# Convert keys to strings, recursively | |
def deep_stringify_keys(hash) | |
transform_hash(hash, :deep => true) {|hash, key, value| | |
hash[key.to_s] = value | |
} | |
end | |
deep_stringify_keys(h) # => {"foo"=>1, "buz"=>4, "bar"=>{"baz"=>3}} | |
# Select a subset of entries | |
def slice_hash(hash, *keys) | |
transform_hash(hash, :deep => true) {|hash, key, value| | |
hash[key] = value if keys.include?(key) | |
} | |
end | |
slice_hash(h, :foo, :buz) # => {:foo=>1, :buz=>4} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment