Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Hash#deep_filter and Hash#deep_remove methods #4748

Closed
wants to merge 2 commits into from
Closed

Add Hash#deep_filter and Hash#deep_remove methods #4748

wants to merge 2 commits into from

Conversation

alexeymuranov
Copy link
Contributor

Here are Hash#deep_filter, #deep_filter!, #deep_remove, and #deep_remove! methods for filtering deep hashes. This can be useful, for example, to filter params in a controller (this is how i am using it).

h = { :a => 1, :b => { :c => 2, :d => 3 }, :e => 4 }
kh = { :a => true, :b => { :c => true } }
h.deep_filter(kh)
# => { :a => 1, :b => { :c => 2 } }
h.deep_remove(kh)
# => { :b => { :d => 3 }, :e => 4 }

I am not sure about names. I was considering deep_only and deep_except, deep_keep and deep_remove, etc.

def deep_remove(key_hash)
new_hash = self.class.new
each_pair do |k,v|
unless key_hash.has_key?(k) && ov = key_hash[k]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

has_key? is for consistency with deep_remove!, where iteration is only over existing keys of key_hash.

@jeremyf
Copy link
Contributor

jeremyf commented May 3, 2012

All of the tests pass.

cc @tenderlove

@alexeymuranov
Copy link
Contributor Author

Any thoughts about the names by the way? 'Filter' sounds too general, can be reserved for more complex operations. Maybe #deep_slice and #deep_except?

@rafaelfranca
Copy link
Member

Hey guys. We think that this kind of things should go to plugins. Active Support is for things that we use in the Rails code and common patterns.

Thank you for the pull request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants