Undef keyword in Ruby
Last Updated :
23 Jul, 2021
Ruby provides a special keyword which is known as undef keyword. This keyword used to avoid the current working class from responding to calls to the specified named methods or variable. Or in other words, once you use under keyword with any method name you are not able to call that method. If you trying to call such type of method, then you will get an error message which says that undefined local variable or method. You can also undefined multiple methods using a single undef keyword.
Syntax:
undef method_name
Let us discuss this concept with the help of the given examples:
Example 1:
Ruby
def portal
puts "Welcome to GeeksforGeeks portal !!"
end
portal
def language
puts "Learn Ruby!"
end
undef language
language
|
Output:
Welcome to GeeksforGeeks portal !!
main.rb:26:in `<main>': undefined local variable or method `language' for main:Object (NameError)
Explanation: In the above example, we have two method, i.e, portal and language. Here, when we call portal method prints “Welcome to GeeksforGeeks portal !!”, but when we call language method it will gives an error massage that is undefine method ‘language’. Because we use undef keyword before language method that makes language method undefined.
Example 2:
Ruby
class Student
def initialize(id, name, branch)
@st_id = id
@st_name = name
@st_branch = branch
puts "ID is: #@st_id"
puts "Name is: #@st_name"
puts "Branch is: #@st_branch"
puts "\n"
end
undef st_id
end
obj1 = Student. new ( "1" , "Amu" , "ECE" )
obj2 = Student. new ( "2" , "Minu" , "EEE" )
|
Output:
main.rb:24:in `<class:Student>': undefined method `st_id' for class `Student' (NameError)
from main.rb:7:in `<main>'
Share your thoughts in the comments
Please Login to comment...