是否可以在 ruby​​ 中取消定义变量? [英] Is it possible to undefine a variable in ruby?

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

问题描述

在 ruby​​ 中,有没有办法在定义变量或常量后取消定义"它?

In ruby, is there a way to "undefine" a variable or constant once it's been defined?

在我们的 rails 环境中,我们将三个常量之一定义为 true,具体取决于环境:TESTINGDEVELOPMENT 或 <代码>生产.然后,在控制器代码中,我们使用 defined? 来查看我们在什么环境中,即:defined?生产.

In our rails environemnts, we define one of three contants to be true, depending on the environment: TESTING, DEVELOPMENT, or PRODUCTION. Then, in controller code, we use defined? to see if what environment we're in, ie: defined? PRODUCTION.

现在,我想对某些特定于环境的行为进行单元测试.我最初的尝试是在我的测试中设置适当的常量,然后在拆卸时重置它们.但是,我不知道如何重置 DEVELOPMENTPRODUCTION 以便 defined? 返回 false.

Now, I want to unit test some of that environment-specific behavior. My initial attempt was to just set the appropriate constant in my test, and then reset them in teardown. However, I can't figure out how to reset DEVELOPMENT and PRODUCTION such that defined? returns false.

显然,除了检查是否已定义,一个解决方案是只检查适当的常量是否也为真,但这将导致不得不接触大量现有代码.

Obviously, a solution would be to just check to see if the appropriate constant is also true in addition to checking if it's defined, but this will result in having to touch a fair amount of existing code.

我意识到这绝对不是正确的做事方式.唉,改变它是一项重要的任务,所以我正在寻找一种简单的方法来对现在的内容进行单元测试.另外,我也很好奇是否可以取消定义变量/常量的低级语言问题.

I realize this is definitely NOT the right way to do things. Alas, changing it is a nontrivial task, so I'm looking for an easy way to just unit test what's there now. Plus, I'm also just curious about the lower level language question of whether it's possible to undefine a variable/constant.

推荐答案

我找到了 这个答案

Object.send(:remove_const, "TESTING")

如果我没记错的话,在这里使用 send 有点像黑客,因为 remove_const 实际上是一个私有方法.您想问自己为什么需要同时定义常量 PRODUCTION、DEVELOPMENT 和 TESTING 而它们实际上是互斥的;这就是为什么我赞成 grepsedawk 的回答.

If I remember correctly, using send here is kind of a hack, because remove_const is really a private method. You want to ask yourself why you need to define constants PRODUCTION, DEVELOPMENT and TESTING at the same time while they really are mutually exclusive ; that's why I upvoted grepsedawk's answer.

这篇关于是否可以在 ruby​​ 中取消定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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