如何检查 Rails 中是否定义了变量?
<% if dashboard_pane_counter.remainder(3) == 0 %>
do something
<% end>
如果未定义 dasboard_pane_counter ,我怎样才能让它计算为 false 而不是抛出异常?
<% if dashboard_pane_counter.remainder(3) == 0 %>
do something
<% end>
If dasboard_pane_counter wasn't defined, how can I get this to evaluate to false rather than throw an exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当使用rails和实例变量时,nil定义了一个
try
方法,所以你可以这样做:所以如果实例变量没有定义,
try(:anything)
将返回nil因此评估为 false。并且nil == 0
为 falseWhen using rails and instance variables, nil has a
try
method defined, so you can do:so if the instance variable is not defined,
try(:anything)
will return nil and therefore evaluate to false. Andnil == 0
is falselocal_assigns 可以用于此目的,因为这个问题是几年前的问题,我验证了它存在于以前版本的 Rails 中,
它位于此处的注释中
http://apidock.com/rails/ActionController/Base/render
local_assigns can be used for that, since this question is from a few years ago, I verified that it exists in previous versions of rails
It's in the notes here
http://apidock.com/rails/ActionController/Base/render
为像我这样的初学者发布这个答案。这个问题可以简单地用两个步骤来回答(如果使用 && 则只需一个步骤)。这是一个更长且不太漂亮的答案,但可以帮助新程序员理解他们在做什么,并使用一种非常简单的技术,该技术尚未出现在任何其他答案中。技巧是使用实例(@)变量,它不适用于局部变量:
如果定义了@foo,它将返回“bar”,否则不会(没有错误)。因此分两步:
Posting this answer for beginner coders like myself. This question can be answered simply using two steps (or one if using &&). It is a longer and less pretty answer but helps new coders to understand what they are doing and uses a very simple technique that is not present in any of the other answers yet. The trick is to use an instance (@) variable, it will not work with a local variable:
If @foo is defined it will be return "bar", otherwise not (with no error). Therefore in two steps:
另一种简洁的方式是“andand”。
https://github.com/raganwald/andand
Another way, with a neat gem, is 'andand.'
https://github.com/raganwald/andand
那
我会使用
更好的 ruby 代码!
Insted of
I would use
Thats much better ruby code!