【发布时间】:2016-09-29 15:23:34
【问题描述】:
我有一些方法包含许多相同逻辑的不同组合。为了清理它,我想每个测试只定义一次。
class Sentence < ApplicationRecord
#Gathers options hash for sentence
def options
{
pronoun: subject.pronoun,
...
}
end
#gives auxiliary verb based on sentence options
def aux
third_person = ["he", "she", "it"].include?(options[:pronoun])
aux = "does" if third_person #just an example
...
end
...
这很好用,但我正在尝试将其从 aux 方法中提取出来,以便在其他方法中使用。
#this works
@@third_person = ["he", "she", "it"].include?("he")
#this says that there is no options method
@@third_person = ["he", "she", "it"].include?(options[:pronoun])
有谁知道,我错过了什么?
【问题讨论】:
-
当我们谈论“清理”时,您需要特别注意的一件事是声明不变,但在这样的方法中丢弃数组。使用像
PREFIXES = %w[ he she it ]这样的常量,然后一遍又一遍地使用该数组。如果存在歧义或性能问题,您也可以使用正则表达式。同样,返回使用过一次的临时哈希是非常低效的,尤其是在哈希永远不会改变的情况下。 -
测试代码的上下文不清楚。你在哪里运行它?另外你为什么要声明类风格的
@@变量? -
我同意@tadman 的观点,即您应该将代词分隔为常量变量。也使用
freeze方法,所以它不能被修改。PREFIXES = %w(he she it).freeze -
好的,很酷,常量没有问题,因为它不会改变。我想我对类变量有点困惑。它似乎不能做我想做的事。我有一个句子的例子。 options 方法获取该实例的选项。我想定义一个使用一次实例选项并可以从其他实例方法访问它的测试。我想另一个实例方法会是要走的路吗?
标签: ruby-on-rails ruby methods