【发布时间】:2016-10-03 18:38:10
【问题描述】:
我已经编写了三四个月的代码(从 Python 开始),由于 Rails 很受欢迎,我才刚刚开始接触 Ruby。
为了帮助我加深对 Ruby 语言的理解,我一直在研究 Ruby Monk 上的问题。 Ruby Primer: Ascent 1.1 - Understanding Inheritance 课程存在以下问题:
编写一个将类和子类作为参数的方法,并返回一个关于子类是否是类的祖先的布尔值。
这是我想出的(注:Ruby Monk 决定用“class”拼写“klass”):
def is_ancestor?(klass, subclass)
subclass.ancestors.map{ |ancestor| ancestor.to_s }.include? klass.to_s
end
此代码通过了所有测试,但声明 doesn't use any other methods to solve the problem (yes, there's a shortcut :)) 的特殊测试除外。
我对如何在不使用其他方法的情况下解决这个问题感到非常恼火,因此我查看了建议的解决方案。这就是 Ruby Monk 所说的答案。
def is_ancestor?(klass, subclass)
current_class = subclass
while !current_class.superclass.nil? && current_class != klass
current_class = current_class.superclass
end
current_class == klass
end
我理解这段代码。我不明白为什么这段代码通过了不使用方法的测试要求,而我的代码没有。毕竟,Ruby Monk 提出的答案确实使用了方法(参见!current_class.superclass.nil)。
我在这里遗漏了什么吗?也许我真的不明白什么是方法。也许我的代码确实可以工作,只是因为 Ruby Monk 正在执行与代码 1:1 匹配的测试而失败。
【问题讨论】:
-
也许是他们不想让你使用的
ancestors方法。您还可以将代码缩短为subclass.ancestors.include?(klass) -
为什么不看看测试是怎么定义的?
-
感谢大家的反馈。我猜 Frederick 和 Aetherus 猜测罪魁祸首是
ancestors是正确的。 @spickermann,据我所知,我无法查看测试是如何定义的。我只能看到他们的输出。
标签: ruby inheritance testing methods