Skip to content

Instantly share code, notes, and snippets.

@treble37
Forked from avdi/map_hash_to_hash.rb
Last active August 29, 2015 13:57
Show Gist options
  • Save treble37/9823228 to your computer and use it in GitHub Desktop.
Save treble37/9823228 to your computer and use it in GitHub Desktop.
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