【问题标题】:Ruby Monk - Understanding Inheritance - Alternate solution not accepted?Ruby Monk - 理解继承 - 不接受替代解决方案?
【发布时间】: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


【解决方案1】:

也许他们不希望您使用mapinclude?,因为它们不是类的方法。它们是数组的方法。

我想这应该可以通过测试。

def is_ancestor?(klass, subclass)
  subclass <= klass
end

嗯,严格来说,&lt;= 也是一种方法。

顺便说一句,如果您可以直接比较类,请不要比较它们的名称。您的原始代码可以优化为

def is_ancestor?(klass, subclass)
  subclass.ancestors.include? klass
end

【讨论】:

    猜你喜欢
    • 2012-08-14
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2011-04-13
    • 2016-10-24
    • 2019-04-09
    相关资源
    最近更新 更多