Created
March 24, 2017 21:01
-
-
Save stephancom/6f0ac16184279c45be0f86c8886d038f to your computer and use it in GitHub Desktop.
recursive hash keys
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
# Returns keys from a hash recursively when that hash can contain hashes | |
# Handy for use with StrongParameters | |
recurse_keys = lambda do |h| h.inject([]) { |a, (k, v)| a << (v.is_a?(Hash) ? { k => recurse_keys.call(v) } : k) } rescue [] end | |
# Example | |
parms = {:foo=>:bar, :baz=>{:a=>:b, :c=>:d, :e=>:f}} | |
recurse_keys.call(parms) | |
# returns [:foo, {baz: [:a, :b, :c]}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This would be handy for implementing strong_parameters
permit!
on certain keys as discussed here:rails/rails#9454