1

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
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • Your condition will be true when `some_var` is empty. I thought you didn't want that. – sawa Apr 13 '11 at 01:51

3 Answers3

3

First of all you might want

unless some_var.nil?

instead.

ALSO you can use an end if at the end of the block

Paul Kaplan
  • 2,885
  • 21
  • 25
2
Blah.where(....).each do |b|
  #...
end if some_var
maerics
  • 151,642
  • 46
  • 269
  • 291
2

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?
Community
  • 1
  • 1
Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106