Ruby Koan 151 raising exceptions

后端 未结 30 1509
孤独总比滥情好
孤独总比滥情好 2021-01-31 14:34

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         


        
相关标签:
30条回答
  • 2021-01-31 15:21

    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
    
    0 讨论(0)
  • 2021-01-31 15:21

    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
    
    0 讨论(0)
  • 2021-01-31 15:21

    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
    
    0 讨论(0)
  • 2021-01-31 15:21

    Rules:

    1. size must be > 0

    2. 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)
    
    0 讨论(0)
  • 2021-01-31 15:22

    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

    0 讨论(0)
  • 2021-01-31 15:24

    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
    
    0 讨论(0)
提交回复
热议问题