Open In App

Defined? Keyword in Ruby

Last Updated : 21 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Ruby provides a special keyword which is known as define? keyword. This keyword is used to check if the passed expression is defined or not. This keyword will return a string describing its expression or argument if the passed expression or argument is defined. Otherwise, it will return nil if the pass expression or argument is not defined. With the help of this keyword, you can check if your variable, class, method, local method, the expression is defined or not. 
Syntax: 
 

defined? variable_name

Let us discuss this concept with the help of the below examples: 
Example 1: 
In this example, we check if the variable is defined or not. 
 

Ruby




# Ruby program to illustrate defined? keyword
 
# Variable
radius = 2
 
area = 3.14 * radius * radius
 
# Checking if the variable is defined or not
# Using defined? keyword
res1 = defined? radius
res2 = defined? height
res3 = defined? area
res4 = defined? Math::PI
 
# Displaying results
puts "Result 1: #{res1}"
puts "Result 2: #{res2}"
puts "Result 3: #{res3}"
puts "Result 4: #{res4}"


Output: 
 

Result 1: local-variable
Result 2: 
Result 3: local-variable
Result 4: constant

Example 2: 
 

Ruby




# Ruby program to illustrate defined? keyword
 
# Method
def geeks
    puts "Hey GeeksforGeeks!!"
end
 
# Checking if the method is defined or not
# Using defined? keyword
res1 = defined? geeks
res2 = defined? fun
res3 = defined? puts
 
# Displaying results
puts "Result 1: #{res1}"
puts "Result 2: #{res2}"
puts "Result 3: #{res3}"


Output: 
 

Result 1: method
Result 2: 
Result 3: method

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads