开发者

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. 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


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


You could look into the AndAnd gem for some inspiration on solving problems with 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?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜