Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - how can I deal with a variable if it doesn't exist

Tags:

ruby

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.

like image 868
junky Avatar asked Dec 12 '22 01:12

junky


1 Answers

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.

like image 163
alf Avatar answered Jan 10 '23 02:01

alf