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?
精彩评论