我正在通过 ruby koans,我在 151 上,我刚撞到一堵砖墙。
这是公案:
# You need to write the triangle method in the file 'triangle.rb'
require 'triangle.rb'
class AboutTriangleProject2 < EdgeCase::Koan
# The first assignment did not talk about how to handle errors.
# Let's handle that part now.
def test_illegal_triangles_throw_exceptions
assert_raise(TriangleError) do triangle(0, 0, 0) end
assert_raise(TriangleError) do triangle(3, 4, -5) end
assert_raise(TriangleError) do triangle(1, 1, 3) end
assert_raise(TriangleError) do triangle(2, 4, 2) end
end
end
然后在 triangle.rb 中我们有:
def triangle(a, b, c)
# WRITE THIS CODE
if a==b && a==c
return :equilateral
end
if (a==b && a!=c) || (a==c && a!=b) || (b==c && b!=a)
return :isosceles
end
if a!=b && a!=c && b!=c
return :scalene
end
if a==0 && b==0 && c==0
raise new.TriangleError
end
end
# Error class used in part 2. No need to change this code.
class TriangleError < StandardError
end
我非常困惑 - 任何帮助都将不胜感激!
编辑:为了完成这个 koan,我需要在 TriangleError 类中添加一些东西 - 但我不知道是什么
更新:这是 koan karma 的意思:
<TriangleError> exception expected but none was thrown.
最佳答案
- 三角形不应有任何长度为 0 的边。如果是,则它要么是线段要么是点,具体取决于有多少条边为 0。
- 负长度没有意义。
- 三角形的任意两条边之和应大于第三条边。
- 查看 3,并关注“更多”。
您不需要更改 TriangleError 代码,AFAICS。看起来你的语法有点古怪。尝试改变
raise new.TriangleError
到
raise TriangleError, "why the exception happened"
此外,在对它们进行任何操作之前,您应该测试这些值(并抛出异常)。将异常内容移到函数的开头。
关于Ruby Koan 151 引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3834203/