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

Accepted answer
Score: 28

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

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

But actually as 2 of 2019 this is no longer needed as both 1 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
Score: 4

On Ruby on Rails

if defined?(mm) && mm.present?
  puts "acceptable variable"


if defined?(mm) && !mm.blank? && !mm.nil?
  puts "acceptable variable"

It can make sure you 6 won't get undefined variable or nil or empty 5 value.

Understand how defined? works

a = 1
defined?(a) # => "local-variable"

b = nil
defined?(b) # => "local-variable"

c = ""
defined?(c) # => "local-variable"

d = []
defined?(d) # => "local-variable"

$e = 'text'
defined?($e) # => "global-variable"

defined?(f) # => nil
defined?($g) # => nil

Note that defined? checks variable in the 4 scope it is.

Why you need defined?

When there is possible of undefined 3 variable presence, you cannot just check 2 it with only .nil? for eaxample, you will have 1 a chance to get NameError.

a = nil
a.nil? # => true
b.nil? # => NameError: undefined local variable or method `b'

More Related questions