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.
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# Variableradius = 2area = 3.14 * radius * radius# Checking if the variable is defined or not# Using defined? keywordres1 = defined? radiusres2 = defined? heightres3 = defined? areares4 = defined? Math::PI# Displaying resultsputs "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# Methoddef geeks puts "Hey GeeksforGeeks!!"end# Checking if the method is defined or not# Using defined? keywordres1 = defined? geeksres2 = defined? funres3 = defined? puts# Displaying resultsputs "Result 1: #{res1}"puts "Result 2: #{res2}"puts "Result 3: #{res3}" |
Output:
Result 1: method Result 2: Result 3: method



