4

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
junky
  • 1,480
  • 1
  • 17
  • 32

2 Answers2

13

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.

Community
  • 1
  • 1
alf
  • 18,372
  • 10
  • 61
  • 92
0
class Object
  def try(*args, &block)
    if args.empty? and block_given?
      begin
        instance_eval &block
      rescue NameError => e
        puts e.message + ' ' + e.backtrace.first
      end
    elsif respond_to?(args.first)
      send(*args, &block)
    end
  end
end

blob = "this is blob"
try { puts blob }
#=> "this is blob"
try { puts something_else } # prints the service message, doesn't raise an error
#=> NameError: undefined local variable or method `something_else' for main:Object
megas
  • 21,401
  • 12
  • 79
  • 130
  • Very similar to `Object#try` in `ActiveSupport`: http://api.rubyonrails.org/classes/Object.html#method-i-try – Michael Kohl Jun 20 '12 at 15:06
  • Yes but I think my version is more convinient. – megas Jun 20 '12 at 15:07
  • Maybe, but the name suggests it's a lot more generic than it actually is by only catching the `NameError`. Things like `try {1/0}` will still fail, so IMHO it's too much for OPs request and too little for a generic solution. – Michael Kohl Jun 20 '12 at 15:47
  • Please, tell me more about generic solution becasue I'm going to build gem for try (it'll be tryit). I don't know how to start chat. – megas Jun 20 '12 at 16:14
  • Well, catch more errors than just `NameError`. Also you probably want to be able to implement different error handling strategies, not just using `puts`. – Michael Kohl Jun 20 '12 at 16:16
  • Whatj might be an error handling strategies? Writing to log file? – megas Jun 20 '12 at 16:20
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/12812/discussion-between-megas-and-michael-kohl) – megas Jun 20 '12 at 16:22