How to check if the variable is defined in Ruby with examples

This tutorial explains about the variable is defined and initialized with a value.

In Ruby language, the Variable is declared and assigned with values.

Check if the variable is defined in Ruby

Ruby provides defined🔗 method.

It checks an expression to check whether it is a variable or assignment or expression or method.

If it is not unable to resolve, returns empty or nil.

number = 11

puts defined?(number)## returns  local-variable
obj  = {}
puts defined?(obj) ## returns  local-variable
str  = nil
puts defined?(str)  ## returns  local-variable

puts defined?(notdeclaredvariable) ## returns empty


puts defined?(@num=1)## returns  assignment

puts defined?(def m; end) ## returns  expression

Output:

local-variable
local-variable
local-variable

assignment
expression

You can also check conditional if expression to return true or false

number = 11
if (defined?(number)).nil?
 puts "number is not defined\n"
else
 puts "number is defined\n"
end

Similarly, you can use unless to check a variable is not defined.

unless defined? number1
    puts "number1 is undefined"
end