Skip to content

Instantly share code, notes, and snippets.

@huezoaa
Forked from avdi/map_hash_to_hash.rb
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huezoaa/cfa156156461398dee98 to your computer and use it in GitHub Desktop.
Save huezoaa/cfa156156461398dee98 to your computer and use it in GitHub Desktop.
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