Created
August 4, 2011 22:09
-
-
Save danneu/1126423 to your computer and use it in GitHub Desktop.
Ruby Koans 151 triangle.rb solution
This file contains 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
def triangle(a, b, c) | |
raise TriangleError if a<=0 or b<=0 or c<=0 | |
raise TriangleError if a+b<=c or b+c<=a or a+c<=b | |
return :equilateral if a==b and a==c | |
return :isosceles if a==b or b==c or a==c | |
:scalene | |
end |
Even better:
def triangle(a, b, c)
a, b, c = sides = [a, b, c].sort
raise TriangleError unless a > 0 and a + b > c
{1 => :equilateral, 2 => :isosceles, 3 => :scalene}[sides.uniq.size]
end
Or even:
def triangle(a, b, c)
a, b, c = sides = [a, b, c].sort
raise TriangleError unless a > 0 and a + b > c
[nil, :equilateral, :isosceles, :scalene][sides.uniq.size]
end
We're really streamlining this little chunk of code. :)
Nice. I get hung up on a tree instead of seeing the forest of refactoring.
I got rid of the nil
, but at this rate we might as well rename sides
to x
. 😔
def triangle(a, b, c)
a, b, c = sides = [a, b, c].sort
raise TriangleError unless a > 0 and a + b > c
[:scalene, :isosceles, :equilateral][-sides.uniq.size]
end
Until next time, team fistbump. 👊
Using a negative index – clever!
Dan & David,
Hi. I'm Rolando. I'm a student at Flatiron School in NYC, and this exchange was super helpful in helping me figure a solution out.
Just wanted to say thanks!
Thanks for all of you guys
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool. My effort to condense your solution:
I didn't like repeating
[a, b, c]
and the only one-liner idea I had was::/