问题描述
以下是koan:
#需要在文件'triangle.rb'中写入三角形方法
require'triangle.rb'
class AboutTriangleProject2< EdgeCase :: Koan
#第一项任务没有讨论如何处理错误。
#现在让我们来处理这个部分。
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)
#写这个代码
如果a == b&& a == c
return:equilateral
end
if(a == b&& a!= c)|| (a == c&& a!= b)|| (b == c&& b!= a)
return:isosceles
end
如果a!= b&& a!= c&& b!= c
return:scalene
end
如果a == 0&& b == 0&& c == 0
raise new.TriangleError
end
$ b $ end
#在第2部分中使用的错误类。无需更改此代码。
class TriangleError< StandardError
end
我非常困惑 - 任何帮助都是非常感谢!
编辑:为了完成这个koan,我需要把一些东西放在TriangleError类中 - 但我不知道什么是
更新:这是koan karma的一句话:
< TriangleError>预期异常,但没有发生。
解决方案当a,b或c是否定的:
pre code $ def三角形(a,b,c)
如果[a,b,c] .min x,y,z = [a,b,c] .sort
如果x + y [:equilateral,:isosceles ,:则会引发TriangleError scalech] .fetch([a,b,c] .uniq.size - 1)
end
I'm going through the ruby koans, I'm on 151 and I just hit a brick wall.
Here is the koan:
# 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
Then in triangle.rb we have:
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
I am beyond confused - any help at all would be much appreciated!
EDIT: To complete this koan, I need to put something in the TriangleError class - but I have no idea what
UPDATE: Here is what the koan karma thing is saying:
<TriangleError> exception expected but none was thrown.
You forgot the case when a,b, or c are negative:
def triangle(a, b, c)
raise TriangleError if [a,b,c].min <= 0
x, y, z = [a,b,c].sort
raise TriangleError if x + y <= z
[:equilateral,:isosceles,:scalene].fetch([a,b,c].uniq.size - 1)
end
这篇关于Ruby Koan 151提出例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!