Ruby 中的 undef 关键字
Ruby 提供了一个特殊的关键字,称为undef关键字。该关键字用于避免当前工作类响应对指定命名方法或变量的调用。或者换句话说,一旦您使用 under 关键字和任何方法名称,您就无法调用该方法。如果您尝试调用此类方法,则会收到一条错误消息,指出未定义的局部变量或方法。您还可以使用单个 undef 关键字取消定义多个方法。
句法:
undef method_name
让我们在给定示例的帮助下讨论这个概念:
示例 1:
Ruby
# Ruby program to illustrate the undef keyword
# Here portal is the method name
def portal
# Statement to be displayed
puts "Welcome to GeeksforGeeks portal !!"
end
# Calling portal method
portal
# Here language is the method name
def language
puts "Learn Ruby!"
end
# Undefine the language method
# Using undef keyword
undef language
# Calling language method
language
Ruby
# Ruby program to illustrate the undef keyword
#!/usr/bin/ruby
# Defining class Student
class Student
# initialize method
def initialize(id, name, branch)
# variables
@st_id = id
@st_name = name
@st_branch = branch
# Displaying values
puts "ID is: #@st_id"
puts "Name is: #@st_name"
puts "Branch is: #@st_branch"
puts "\n"
end
# Using undef keyword
undef st_id
end
# Creating objects and passing parameters
# to new method
obj1 = Student.new("1", "Amu", "ECE")
obj2 = Student.new("2", "Minu", "EEE")
输出:
Welcome to GeeksforGeeks portal !!
main.rb:26:in `': undefined local variable or method `language' for main:Object (NameError)
说明:在上面的例子中,我们有两种方法,即门户和语言。在这里,当我们调用门户方法时打印“欢迎来到 GeeksforGeeks 门户!”,但是当我们调用语言方法时,它会给出一个错误消息,即未定义方法“语言”。因为我们在使语言方法未定义的语言方法之前使用了 undef 关键字。
示例 2:
红宝石
# Ruby program to illustrate the undef keyword
#!/usr/bin/ruby
# Defining class Student
class Student
# initialize method
def initialize(id, name, branch)
# variables
@st_id = id
@st_name = name
@st_branch = branch
# Displaying values
puts "ID is: #@st_id"
puts "Name is: #@st_name"
puts "Branch is: #@st_branch"
puts "\n"
end
# Using undef keyword
undef st_id
end
# Creating objects and passing parameters
# to new method
obj1 = Student.new("1", "Amu", "ECE")
obj2 = Student.new("2", "Minu", "EEE")
输出:
main.rb:24:in `': undefined method `st_id' for class `Student' (NameError)
from main.rb:7:in `'