{

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

Difference between put and println in Ruby with examples

How to check a string contains a substring in Ruby with examples

How to check if element exists in hash or not in Ruby with examples

How to check if an element exists in Array or not in Ruby with examples

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

How to convert Class or Hash Object to JSON Object Ruby| Ruby on Rails By Example

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