Ruby on Rails:删除多个哈希键 [英] Ruby on Rails: Delete multiple hash keys

查看:31
本文介绍了Ruby on Rails:删除多个哈希键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己在写这个:

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?

推荐答案

我猜你不知道 Hash#except 方法 ActiveSupport 添加到 Hash.

I'm guessing you're unaware of the Hash#except method ActiveSupport adds to Hash.

它将允许您的代码简化为:

It would allow your code to be simplified to:

redirect_to my_path(params.except(:controller, :action, :other_key))

此外,您不必进行猴子补丁,因为 Rails 团队为您完成了!

Also, you wouldn't have to monkey patch, since the Rails team did it for you!

这篇关于Ruby on Rails:删除多个哈希键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆