I want do puts blob
but if the blob variable doesn’t exist, I get
NameError: undefined local variable or method `blob' for main:Object
I’ve tried
blob?
blob.is_a?('String')
puts "g" if blob
puts "g" catch NameError
puts "g" catch 'NameError'
but none work.
I can get around it by using an @instance variable but that feels like cheating as I should know about and deal with the issue of no value accordingly.
In this case, you should do:
Or, if you want to check for nil too:
The
defined?method returns a string representing the type of the argument if it is defined, ornilotherwise. For example:The typical way of using it is with conditional expressions:
More about
defined?on this question.