Last active
          March 21, 2022 08:23 
        
      - 
      
- 
        Save nickangtc/a467cd5de1a8fe08becfeb3f434886d1 to your computer and use it in GitHub Desktop. 
    an example of beautiful ruby code used to validate a triangle as part of ruby koans exercise
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # exercise is from http://rubykoans.com/ - a great way to learn ruby! | |
| #! my not so succinct but works solution | |
| def triangle(a, b, c) | |
| validate_triangle(a, b, c) | |
| if a == b && b == c | |
| :equilateral | |
| elsif a != b && b != c && c != a | |
| :scalene | |
| else | |
| :isosceles | |
| end | |
| end | |
| def validate_triangle(a, b, c) | |
| raise TriangleError, "No such thing as negative or 0-length sides in a triangle" if a <= 0 || b <= 0 || c <= 0 | |
| raise TriangleError, "Incomplete triangle because the sides cannot touch and close up" if a + b <= c || a + c <= b || b + c <= a | |
| end | |
| # === | |
| # Josh's beautiful solution taken from https://stackoverflow.com/a/14445542/6463816 | |
| # === | |
| def triangle(a, b, c) | |
| [a, b, c].permutation do |sides| | |
| raise TriangleError unless sides[0] + sides[1] > sides[2] | |
| end | |
| case [a,b,c].uniq.size | |
| when 3; :scalene | |
| when 2; :isosceles | |
| when 1; :equilateral | |
| end | |
| end | |
| class TriangleError < StandardError | |
| end | 
Rather than sides[0] + sides[1] > sides[2], what about sides[0..1].sum > sides[2]?
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
[].permutationis so easy to understand as a human! line 24[].uniq.sizeandwhen Nexpress the thing I'm trying to do in the form closest to how I think about it in my human mind. line 27