Defined? Keyword in Ruby
Last Updated :
21 Jul, 2021
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
radius = 2
area = 3 . 14 * radius * radius
res1 = defined ? radius
res2 = defined ? height
res3 = defined ? area
res4 = defined ? Math:: PI
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
def geeks
puts "Hey GeeksforGeeks!!"
end
res1 = defined ? geeks
res2 = defined ? fun
res3 = defined ? puts
puts "Result 1: #{res1}"
puts "Result 2: #{res2}"
puts "Result 3: #{res3}"
|
Output:
Result 1: method
Result 2:
Result 3: method
Share your thoughts in the comments
Please Login to comment...