有没有一种干净的方法来避免在嵌套的params散列中调用nil方法? [英] Is there a clean way to avoid calling a method on nil in a nested params hash?
本文介绍了有没有一种干净的方法来避免在嵌套的params散列中调用nil方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有兴趣获取params散列的嵌套'name'参数。调用类似于
params [:subject] [:name]
$当params [:subject]为空时,p $ p>
会引发错误。为避免这种错误,我通常会写这样的内容:
if params [:subject]&& params [:subject] [:name]
是否有一个更简洁的方法来实现它?
解决方案检查 Ick 的也许。您不需要对代码进行重构,只需在必要时使用代理即可:
[:subject] .maybe [:name]
同一作者( raganwald )也写了 andand ,具有相同的想法。
I'm interested in getting the nested 'name' parameter of a params hash. Calling something like
params[:subject][:name]
throws an error when params[:subject] is empty. To avoid this error I usually write something like this:
if params[:subject] && params[:subject][:name]
Is there a cleaner way to implement this?
解决方案
Check Ick's maybe. You don't need to significantly refactor your code, just intersperse maybe proxies when necessary:
params[:subject].maybe[:name]
The same author (raganwald) also wrote andand, with the same idea.
这篇关于有没有一种干净的方法来避免在嵌套的params散列中调用nil方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文