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.
This tutorial explains about the variable is defined and initialized with a value.
In Ruby language, the Variable is declared and assigned with values.
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
🧮 Tags
Recent posts
Puppeteer Login Test example How to convert Double to Integer or Integer to double in Dart| Flutter By Example Best ways to fix 504 gateway time out in nodejs Applications Fix for Error No configuration provided for scss Multiple ways to List containers in a Docker with examplesRelated posts