Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Ruby%20On%20Rails%20Interview%20Questions%20and%20Answers

Question: How can you call the base class method from inside of its overridden method?
Answer:

If you are inside the overridden method in the derived class then a simple call to super will call the right method in the base class

class Parent
   def try_this()
      puts "parent"
   end
end

class Child < Parent
   def try_this()
      super()
      puts "child"
   end
end

ch = Child.new
ch.try_this()

This generates the output

parent
child

Now if you just want to call the base class without calling the derived class then the best way to do that is to simply assign an alias to the parent method like this:

class Parent
  def knox
    puts 'parent'
  end
end
 
class Child < Parent
   alias_method :parent_knox, :knox
   def knox
     puts 'child'
   end
end
 
ch = Child.new
ch.parent_knox
ch.knox

This allows you to call the base class method with the alias parent_knox and the derived class method knox can be called directly.

parent
child
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook