Defined? Keyword in Ruby

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.
Synatx:

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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}"

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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}"

chevron_right


Output:

Result 1: method
Result 2: 
Result 3: method



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.