Skip to content

Instantly share code, notes, and snippets.

@avdi
Created November 20, 2009 15:32
Show Gist options
  • Save avdi/239563 to your computer and use it in GitHub Desktop.
Save avdi/239563 to your computer and use it in GitHub Desktop.
def map_hash_to_hash(original, options={})
original.inject({}){|a, (key,value)|
catch(:skip) do
value = if (options[:deep] && Hash === value)
map_hash_to_hash(value) {|k,v| yield(k, v) }
else
value
end
new_key, new_value = yield(key,value)
a[new_key] = new_value
end
a
}
end
h = { :foo => 1, :bar => {:baz => 3}, :buz => 4 }
h.map{|k,v| [k.to_s, v]} # => [["buz", 4], ["foo", 1], ["bar", {:baz=>3}]]
# Convert keys to strings
def stringify_keys(hash)
map_hash_to_hash(hash) {|key, value|
[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)
map_hash_to_hash(hash, :deep => true) {|key, value|
[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)
map_hash_to_hash(hash, :deep => true) {|key, value|
throw :skip unless keys.include?(key)
[key, value]
}
end
slice_hash(h, :foo, :buz) # => {:buz=>4, :foo=>1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment