[英]How to wrap a code block using an if statement, meaning is there a ruby way to do this?
我有一个这样的块:
Blah.where(....).each do |b|
# Code here
end
我只想在some_var
不是nil
或为空的情况下运行它。 除了:
if !some_var.nil
Blah.where(....).each do |b|
# Code here
end
end
首先,您可能想要
unless some_var.nil?
代替。
还可以在代码块的末尾使用end if
Blah.where(....).each do |b|
#...
end if some_var
您可以查看AndAnd gem,以获取有关解决nil问题的一些启发。 有关概述, 请在此处查看我的答案 。
否则,可能最好的方法是
Blah.where(...).each do |a|
...
end unless some_var.nil?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.