Saturday, February 19, 2011

Checking if a variable is defined in Ruby

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

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

  • 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"
    
  • 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

  • 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
    

0 comments:

Post a Comment