tags:

views:

5483

answers:

4

How do you check whether a variable is defined in Ruby? Is there an "isset"-type method available?

+8  A: 

defined?(your_var) will work. Depending on what you're doing you can also do something like your_var.nil?

digitalsanctum
+19  A: 

use defined? It will return a string with the kind of the item or nil if it don't exist

irb(main):007:0> a = 1
=> 1
irb(main):008:0> defined? a
=> "local-variable"
irb(main):009:0> defined? b
=> nil
irb(main):010:0> defined? String
=> "constant"
irb(main):011:0> defined? 1
=> "expression"
Ricardo Acras
+5  A: 

this is useful if you want to do nothing if it does exist but create it if it doesn't exist

def get_var
  @var ||= SomeClass.new()
end

this only creates the new class once after that just keeps returning the var

danmayer
A: 

Here is some code, nothing rocket science but it works well enough

require 'rubygems'
require 'rainbow'
if defined?(var).nil?
 print "var is not defined\n".color(:red)
else
 print "car is defined\n".color(:green)
end
Sardathrion