简体   繁体   中英

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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