本文介绍了Ruby:IF语句中的Nils的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
...如果没有参数或没有搜索参数,我得到一个错误。
当然必须有更好的方法来做到这一点......建议
解决方案
if defined?(params [:search] [:tags_name_in])
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??
解决方案
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!