Ruby on Rails:删除多个哈希键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1560572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails: Delete multiple hash keys
提问by Mark Westling
I often find myself writing this:
我经常发现自己在写这个:
params.delete(:controller)
params.delete(:action)
params.delete(:other_key)
redirect_to my_path(params)
The trail of deletes doesn't feel right and neither does:
删除的轨迹感觉不对,也不是:
[:controller, :action, :other_key].each do |k|
params.delete(k)
end
Is there anything simpler and cleaner?
有没有更简单更干净的东西?
回答by Ben Crouse
I'm guessing you're unaware of the Hash#exceptmethod ActiveSupport adds to Hash.
我猜您不知道ActiveSupport 添加到 Hash的Hash#except方法。
It would allow your code to be simplified to:
它将允许您的代码简化为:
redirect_to my_path(params.except(:controller, :action, :other_key))
Also, you wouldn't have to monkey patch, since the Rails team did it for you!
此外,您不必进行猴子补丁,因为 Rails 团队为您完成了!
回答by Mark Westling
While using Hash#excepthandles your problem, be aware that it introduces potential security issues. A good rule of thumb for handling any data from visitors is to use a whitelist approach. In this case, using Hash#sliceinstead.
在使用Hash#except处理您的问题时,请注意它会引入潜在的安全问题。处理来自访问者的任何数据的一个很好的经验法则是使用白名单方法。在这种情况下,使用Hash#slice代替。
params.slice!(:param_to_remove_1, :param_to_remove_2)
redirect_to my_path(params)
回答by Bob Aman
I'd be completely happy with the code you originally posted in your question.
我对您最初在问题中发布的代码感到非常满意。
[:controller, :action, :other_key].each { |k| params.delete(k) }
回答by Mike Seplowitz
Another way to phrase dmathieu's answer might be
表达 dmathieu 答案的另一种方式可能是
params.delete_if { |k,v| [:controller, :action, :other_key].include? k }
回答by tadman
Fire up a monkey patch?
启动猴子补丁?
class Hash
def delete_keys!(*keys)
keys.flatten.each do |k|
delete(k)
end
self
end
def delete_keys(*keys)
_dup = dup
keys.flatten.each do |k|
_dup.delete(k)
end
_dup
end
end
回答by Pesto
I don't know what you think is wrong with your proposed solution. I suppose you want a delete_allmethod on Hash or something? If so, tadman's answerprovides the solution. But frankly, for a one-off, I think your solution is extremely easy to follow. If you're using this frequently, you might want to wrap it up in a helper method.
我不知道您认为您提出的解决方案有什么问题。我想你想要一个delete_all关于 Hash的方法之类的?如果是这样,tadman 的回答提供了解决方案。但坦率地说,对于一次性,我认为您的解决方案非常容易遵循。如果您经常使用它,您可能希望将它包装在一个辅助方法中。

