Ruby Koan 151 raising exceptions

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

      #(1)Any zero or -ve values
      if [a,b,c].any? { |side_length| side_length <= 0 }
        raise TriangleError
      end
    
      #(2)Any side of a triangle must be less than the sum of the other two sides
      # a <  b+c, b <  a+c  and c <  a+b  a  valid   triangle
      # a >= b+c, b >= a+c  and c >= a+b  an invalid triangle
    
      total_of_side_lengths = [a,b,c].inject {|total,x| total += x}
    
      if [a,b,c].any? { |side_length| side_length >= (total_of_side_lengths - side_length)}
        raise TriangleError
      end
    

提交回复
热议问题