Skip to content
Related Articles

Related Articles

Improve Article

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




# 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

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




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

Output:  

main.rb:24:in `<class:Student>': undefined method `st_id' for class `Student' (NameError)
    from main.rb:7:in `<main>'



My Personal Notes arrow_drop_up
Recommended Articles
Page :