Ruby Koan 151 raising exceptions

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

    def triangle(a, b, c)
    
      sides = a, b, c # Assigns variable signs (array) to all arguments.
      begin
    
      raise TriangleError if sides.inject(:+) <= 0 # Raise an error if all sides added together are less than or equal to 0. (the triangle would be invalid).
      raise TriangleError if sides.any?(&:negative?) #Raise an error if there are any negative sides.
      sides.each {|side| (side < (sides.inject(:+) - side) ? nil : (raise TriangleError))} # For the final check, Raise an error if any single side is greater than the other two sides added together. It can be broken down like this if side is less than (remaining sides - side we're comparing) raise an error, else, nil. 
    
      return :equilateral if sides.uniq.length == 1
      return :isosceles   if sides.uniq.length == 2
      return :scalene     if sides.uniq.length == 3
    
      resuce TriangleError
      end
    end
    

提交回复
热议问题