Thursday, July 22, 2010

Ruby - "defined?" method

Hi all,

In ruby we are having many methods to check whether the variable defined or not. Mostly we are using the following condition to check the variable defined or not

Code:
if local_variable
puts "local variable exists"
else
puts "local_variable does not exists"
end

But there is another way to check the variable defined or not.

sample-code:

a = 10
puts defined?(a).inspect => "local-variable"
puts defined?(b).inspect => nil

So, the method returns the value "local-variable" for the already defined variables and "nil" for the undefined variables.

Hope hereafter you guys using the method "defined?" to check the variable already defined or not.

Cheers,
Vadivelan