Ruby-on-rails 如何检查是否在 rails 中定义了变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7806133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check if a variable is defined in rails?
提问by cjm2671
<% 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?
如果未定义 dasboard_pane_counter ,我怎样才能让它评估为 false 而不是抛出异常?
回答by Matt
<% if defined?(:dashboard_pane_counter) && dashboard_pane_counter.remainder(3) == 0 %>
# do_something here, this assumes that dashboard_pane_counter is defined, but not nil
<% end %>
回答by Yule
When using rails and instance variables, nil has a trymethod defined, so you can do:
使用 rails 和实例变量时, niltry定义了一个方法,因此您可以执行以下操作:
<% if @dashboard_pane_counter.try(:remainder(3)) == 0 %>
#do something
<% end %>
so if the instance variable is not defined, try(:anything)will return nil and therefore evaluate to false. And nil == 0is false
因此,如果未定义实例变量,try(:anything)将返回 nil 并因此评估为 false。而且nil == 0是假的
回答by katzmopolitan
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
local_assigns 可以用于这个,因为这个问题是几年前的,我确认它存在于以前版本的 rails 中
<% if local_assigns[:dashboard_pane_counter]
&& dashboard_pane_counter.remainder(3) == 0%>
<% end %>
It's in the notes here
它在此处的注释中
回答by Dennis
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
"bar"
end
If @foo is defined it will be return "bar", otherwise not (with no error). Therefore in two steps:
如果定义了@foo,它将返回“bar”,否则返回(没有错误)。因此分两步:
if @dashboard_pane_counter
if @dashboard_plane_counter.remainder(3) == 0
do something
end
end
回答by andrewpthorp
回答by davidb
Insted of
插入的
if !var.nil?
I would use
我会用
unless var.nil?
Thats much better ruby code!
那是更好的 ruby 代码!

