Forum: Ruby can we modify the method defination once it is defined inside a class?

Posted by Xavier R. (arup_r)
on 2013-02-27 23:05
Hi,

Suppose I have written the below code:

class Foo

def show

p "Good"

end

end

Now is it possible in future to re-open the "show" method again to add
some new logic,once the `class Foo` has been defined ?
Posted by Hans Mackowiak (hanmac)
on 2013-02-27 23:13
look for alias and alias_method
Posted by Calvin B. (calvin_b)
on 2013-02-27 23:45
(Received via mailing list)
Hello Xavier,

yes, it is possible. There are three options you have, depending on what
you want:
  - Inheritance: Overwrite the method show in a subclass and then call
super (if you need the new behavior independently of the old behavior)
  - Alias the old method show to something like "old_show" and then
redefine show (if you want to call the old method); alias_method and
alias are the tools for that
  - Just redefine the method (if you don't need the old method)

Kind regards,

Calvin
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.