Ruby:IF 语句中的 Nils
我正在开发的 Rails 应用程序中有以下非常丑陋的 ruby 代码:
if params.present?
if params[:search].present?
if params[:search][:tags_name_in].present?
...
end
end
end
我想问的是 params[:search][:tags_name_in] 是否已定义,但因为 params 和 params[:search] ,并且 params[:search][:tags_name_in] 可能全部为零,如果我使用...
if params[:search][:tags_name_in].present?
...如果没有参数或没有搜索参数,我会收到错误。
当然必须有更好的方法来做到这一点......建议?
I have the following very ugly ruby code in a rails app I'm working on:
if params.present?
if params[:search].present?
if params[:search][:tags_name_in].present?
...
end
end
end
All I'm trying to ask is whether params[:search][:tags_name_in] has been defined, but because params, and params[:search], and params[:search][:tags_name_in] might all be nil, if I use...
if params[:search][:tags_name_in].present?
... I get an error if there are no params or no search params.
Surely there must be a better way to do this... suggestions??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您只是想看看它是否已定义,为什么不保持简单并使用已定义的呢?功能?
if you are just trying to see if its defined why not keep it simple and use the defined? function?
参数将始终被定义,因此您可以删除它。
要减少代码量,您可以执行以下操作:
如果未定义
params[:search]
,则条件将短路并返回nil
。Params will always be defined, so you can remove that.
To reduce the amount of code you can do
If
params[:search]
is not defined, the condition will short circuit and returnnil
.您可以使用 andand 来实现此目的。它处理这种确切的情况:
if params[:search].andand[:tags_name_in].andand.present?
You can use andand for this. It handles this exact situation:
if params[:search].andand[:tags_name_in].andand.present?
您有多种选择,如果
params[:search]
为 <,则返回params[:search][:tags_name_in]
或nil
值代码>零。清晰但冗长:
使用
try
(来自active_support
):使用救援:
使用
fetch
:请注意,
fetch
有时可以用于完全避免if
,特别是在未指定参数时无事可做的情况下:You have many choices that will return the value of
params[:search][:tags_name_in]
ornil
ifparams[:search]
isnil
.Clear but lengthy:
Using
try
(fromactive_support
):Using rescue:
Using
fetch
:Note that
fetch
can sometime be used to avoid theif
altogether, in particular if there is nothing to do when the param is not specified:哈哈,如果你想变得可怕,monkeypatch nil:
不过,我会推荐一个短路 if 就像其他答案所建议的那样。
Haha, if you want to be terrible and monkeypatch nil:
I would recommend a short-circuited if like the other answers suggest, though.
我通常最终会做这样的事情:
尽管如果您不介意在 if 语句中测试 nils,您也可以这样做:
这不会引发错误,因为 ruby 短路 &&操作员。
I usually end up doing something like this:
Although if you don't mind testing against nils in your if statement you could also do this:
This will not throw an error because ruby short-circuits the && operator.