Search code examples
classrhomobile

how to check that class variable @@abc is initialized or not in rhomobile?


I need a condition in my rhodes app to check if a class variable @@abc is initialized then do something else something.

How can i get this done?


Solution

  • Try using defined?

    if defined?(your variable)
      do something
    else
      do something else
    end
    

    If the variable is defined, you'll receive back a string with the kind of the variable, otherwise defined? will return nil. beware that defined?(nil) will return the string "nil", not the value nil.

    There's also a very ruby idiomatic way to do something akin to "if not defined do this", which is

    x ||= something
    

    Quick examples:

    $ irb
    >> x = 1
    => 1
    >> x
    => 1
    >> defined? x
    => "local-variable"
    >> defined? y
    => nil
    >> y ||= 42
    => 42
    >> defined? y
    => "local-variable"
    >> z = 3
    => 3
    >> z ||= 43
    => 3
    >> defined? nil
    => "nil"
    >>