Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

undef - Why would you want to undefine a method in ruby?

I've never seen undef - or any thing else that allows you to undefine a method - in any other programming languages. Why is it needed in Ruby?

EDIT: I'm not arguing that there is anything wrong with this. I just don't understand the purpose of defining methods at runtime? What's the purpose of that? How is it used? I've never done this in C or Java.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's also the blank class pattern in Ruby that needs the undef functionality.

The idea is to strip every method from your new class so that every call you make to it ends in #method_missing. That way you can implement a real proxy that just shuffles everything through. Implementing the decorator pattern with this is around ten lines of code, no matter how big your target class is.

If you want to see that idiom in action look at one of Ruby's mocking frameworks, they use it alot. Something like flexmock.

Another example is when you add functions dynamicly onto a class based on some condition. In a game you might add an #attack method onto the player object and then take it away when he′s paralyzed instead of doing it with a boolean flag. That way the calling class can check for the availabty of the method and not the flag. I′m not saying that this is a good idea, just that it′s made possible and there are far smarter people then me coming up with useful stuff to do with this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...