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 \'trian
You don't need to modify the Exception. Something like this should work;
def triangle(*args)
args.sort!
raise TriangleError if args[0] + args[1] <= args[2] || args[0] <= 0
[nil, :equilateral, :isosceles, :scalene][args.uniq.length]
end
In fact in the following code the condition a <= 0 is redundant. a + b will always be less than c if a < 0 and we know that b < c
raise TriangleError if a <= 0 || a + b <= c
Here is my version... :-)
def triangle(a, b, c)
if a <= 0 || b <= 0 || c <= 0
raise TriangleError
end
if a + b <= c || a + c <= b || b + c <= a
raise TriangleError
end
return :equilateral if a == b && b == c
return :isosceles if a == b || a == c || b == c
return :scalene if a != b && a != c && b != c
end
Rules:
size must be > 0
Total of any 2 sides, must be bigger that the 3rd
Code:
raise TriangleError if ( [a,b,c].any? {|x| (x <= 0)} ) or ( ((a+b)<=c) or ((b+c)<=a) or ((a+c)<=b))
[:equilateral, :isosceles, :scalene].fetch([a,b,c].uniq.size - 1)
You have to check that the new created triangle don't break the "Triangle inequality". You can ensure this by this little formula.
if !((a-b).abs < c && c < a + b)
raise TriangleError
end
When you get the Error:
<TriangleError> exception expected but none was thrown.
Your code is probably throwing an exception while creating a regular triangle in this file. about_triangle_project.rb
Not that this question needed another answer; however, I think this is the simplest and most readable solution. Thanks to all those before me.
def triangle(a, b, c)
a, b, c = [a, b, c].sort
raise TriangleError, "all sides must > 0" unless [a, b, c].min > 0
raise TriangleError, "2 smaller sides together must the > 3rd side" unless a + b > c
return :equilateral if a == b && a == c
return :isosceles if a == b || a == c || b == c
return :scalene
end
# Error class used in part 2. No need to change this code.
class TriangleError < StandardError
end