How to check if a variable exists with a value without "undefined local variable or method"?

Michael Durrant picture Michael Durrant · Aug 24, 2012 · Viewed 30.8k times · Source

This is a common pattern: If a variable doesn't exist I get an undefined local variable or method error.

The existing code has if variable_name.present? but this didn't account for the variable not existing.

How can I check the value of the variable and also account for it not existing at all?

I've tried:

if (defined? mmm) then
  if mmm.present? then
    puts "true"
  end
end

but Ruby still checks that inner mmm.present? and throws "no such variable" when it doesn't exist.

I'm sure there's a common pattern/solution to this.

Answer

Michael Durrant picture Michael Durrant · Aug 24, 2012

Change the present? to != '' and use the && operator which only tries to evaluate the seond expression if the first one is true:

if defined?(mmm) && (mmm != '') then puts "yes" end

But actually as of 2019 this is no longer needed as both the below work

irb(main):001:0> if (defined? mm) then
irb(main):002:1* if mm.present? then
irb(main):003:2* p true
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> if (defined? mm) then
irb(main):007:1* p mm
irb(main):008:1> end
=> nil