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:
puts blob if defined?(blob)
Or, if you want to check for nil too:
puts blob if defined?(blob) && blob
The defined?
method returns a string representing the type of the argument if it is defined, or nil
otherwise. For example:
defined?(a)
=> nil
a = "some text"
=> "some text"
defined?(a)
=> "local-variable"
The typical way of using it is with conditional expressions:
puts "something" if defined?(some_var)
More about defined?
on this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With