📜  定义? Ruby中的关键字

📅  最后修改于: 2022-05-13 01:54:58.374000             🧑  作者: Mango

定义? Ruby中的关键字

Ruby 提供了一个特殊的关键字,称为define?关键词。此关键字用于检查传递的表达式是否已定义。如果定义了传递的表达式或参数,此关键字将返回描述其表达式或参数的字符串。否则,如果未定义传递表达式或参数,它将返回 nil。借助此关键字,您可以检查您的变量、类、方法、本地方法、表达式是否已定义。
句法:

defined? variable_name

让我们借助以下示例来讨论这个概念:
示例 1:
在此示例中,我们检查变量是否已定义。

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


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


输出:

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

示例 2:

红宝石

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

输出:

Result 1: method
Result 2: 
Result 3: method