Ruby Koan 151 raising exceptions

后端 未结 30 1596
孤独总比滥情好
孤独总比滥情好 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: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
    

提交回复
热议问题