简体   繁体   English

如何使用if语句包装代码块,这意味着有红宝石的方法吗?

[英]How to wrap a code block using an if statement, meaning is there a ruby way to do this?

I have a block like this: 我有一个这样的块:

Blah.where(....).each do |b|
  # Code here
end

I only want to run this if some_var is not nil or empty. 我只想在some_var不是nil或为空的情况下运行它。 Is there a ruby way to do this other than: 除了:

if !some_var.nil
  Blah.where(....).each do |b|
    # Code here
  end
end

First of all you might want 首先,您可能想要

unless some_var.nil?

instead. 代替。

ALSO you can use an end if at the end of the block 还可以在代码块的末尾使用end if

Blah.where(....).each do |b|
  #...
end if some_var

You could look into the AndAnd gem for some inspiration on solving problems with nil. 您可以查看AndAnd gem,以获取有关解决nil问题的一些启发。 For an overview check out my answer here . 有关概述, 请在此处查看我的答案

Other then that the probably best way is to do 否则,可能最好的方法是

Blah.where(...).each do |a|
   ...
end unless some_var.nil?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM