undef - 为什么要在 ruby​​ 中取消定义方法? [英] undef - Why would you want to undefine a method in ruby?

查看:23
本文介绍了undef - 为什么要在 ruby​​ 中取消定义方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从未在任何其他编程语言中看到 undef - 或任何其他允许您取消定义方法的东西.为什么在 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?

我不是说这有什么问题.我只是不明白在运行时定义方法的目的?这样做的目的是什么?它是如何使用的?我从来没有用 C 或 Java 做过这件事.

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.

推荐答案

Ruby 中还有一个需要 undef 功能的空白类模式.

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

这个想法是从你的新类中剥离每个方法,这样你对它的每次调用都以 #method_missing 结束.这样你就可以实现一个真正的代理,它只是把所有东西都打乱了.无论您的目标类有多大,用它实现装饰器模式都需要大约十行代码.

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.

如果您想了解该习惯用法,请查看 Ruby 的模拟框架之一,他们经常使用它.类似于 flexmock.

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

另一个例子是当您根据某些条件将函数动态添加到类中时.在游戏中,您可能会在玩家对象上添加一个 #attack 方法,然后在他瘫痪时将其移除,而不是使用布尔标志来执行此操作.这样调用类可以检查方法的可用性而不是标志.我并不是说这是个好主意,只是说它已经成为可能,而且有比我更聪明的人想出有用的东西来解决这个问题.

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.

这篇关于undef - 为什么要在 ruby​​ 中取消定义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆