{

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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to print the name of a Ruby class| Ruby on Rails By Example

How to Find the minimum and maximum values in an array and hash Ruby with examples

How to Generate Random number in Ruby with examples

How to Get current Unix timestamp or milliseconds since epoch Ruby Programming| Ruby on Rails by Example