Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add statements to an existing method definition in Ruby

I noticed for the class definition, if I open up the class MyClass, and add something in between without overwrite I still got the original method which defined earlier. The new statements added augment the existing one.

But as to the method definition, I still want the same behavior as the class definition, but it seems when I open up the def my_method, the exiting statements within the def and end is overwritten, I need to rewrite that again.

So is there any way to make the method definition behave the same as definition, something like super, but not necessarily is the sub-class?

like image 320
mko Avatar asked Aug 06 '11 12:08

mko


People also ask

What does .include do in Ruby?

The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins).

What does .call do in Ruby?

The purpose of the . call method is to invoke/execute a Proc/Method instance.

What does def mean in Ruby?

When Ruby executes the def keyword, it simply redefines it (whether the method already exists or not). This is called overriding. See the following example : def language puts("We are learning PHP") end def language puts("We are learning Ruby") end # Now call the method language.

How do you write a method in Ruby?

Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly. Methods should be defined before calling them, otherwise Ruby will raise an exception for undefined method invoking.


1 Answers

I suppose you are looking for alias_method:

class A
  alias_method :old_func, :func

  def func
    old_func # similar to calling 'super'
    # do other stuff
  end
end
like image 91
emboss Avatar answered Oct 12 '22 00:10

emboss