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

前端 未结 7 620
无人共我
无人共我 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:35

    Related to defining methods at runtime is the technique of including modules as needed. I work on a Rails application where we sometimes have to export data in various formats. 99% of the time, the Form object doesn't need export-related methods, but in our exporting Rake task, we do something like:

    Form.send(:include, FormExportingMethods)
    

    So it only has those methods when it needs them.

    This sort of dynamism is one of the things I love about Ruby. Whereas in some languages, you have to define your classes and objects up front, Ruby lets you say "oh, I need my pig to have wings right now? I'll just attach them."

    Notice in my example that specific form objects aren't being modified; the Form class is. This works because, when you send a message to an object, it searches its method lookup chain for a response at the moment you ask. So you can create an object, then add a method anywhere in its inheritance chain, then call the method on the object, and it will have it. Obviously, having to look through the whole inheritance chain for each method call is expensive, but it's a trade-off for this kind of flexibility.

    0 讨论(0)
提交回复
热议问题