Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.