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

前端 未结 7 624
无人共我
无人共我 2020-12-15 09:41

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 arguin

7条回答
  •  抹茶落季
    2020-12-15 10:18

    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.

提交回复
热议问题