Ruby:IF 语句中的 Nils [英] Ruby: Nils in an IF statement

查看:19
本文介绍了Ruby:IF 语句中的 Nils的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发的 Rails 应用中有以下非常难看的 ruby​​ 代码:

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

我想问的是 params[:search][:tags_name_in] 是否已定义,但因为 params、params[:search] 和 params[:search][:tags_name_in] 可能都为零,如果我使用...

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??

推荐答案

如果您只是想看看它是否已定义,为什么不保持简单并使用已定义的?功能?

if you are just trying to see if its defined why not keep it simple and use the defined? function?

if defined?(params[:search][:tags_name_in])

这篇关于Ruby:IF 语句中的 Nils的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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